Why are my AJAX requests not extending an OWIN MVC session?
Asked Answered
J

1

12

We have an ASP.NET MVC 5 application that has been using Forms Authentication with sliding expiration. We recently switched to OWIN Cookie Authentication and are experiencing issues with our sessions not extending properly.

Previously, a session could be extended from an AJAX xhr request. With this configuration, however, they are not extending. I'm receiving a 200 for every request (both GET and POST) that should be extending, even after the server has killed the session.

The current setup is:

app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

UrlHelper url = new UrlHelper(HttpContext.Current.Request.RequestContext);
app.UseCookieAuthentication(new CookieAuthenticationOptions()
{
   AuthenticationType = "Cookies",
   CookieSecure = CookieSecureOption.SameAsRequest,
   CookieName = Constants.CatalystPortalCookieName,
   LoginPath = new PathString(url.Action(nameof(LoginController.Index), "Login")),
   SlidingExpiration = true,
   ExpireTimeSpan = TimeSpan.FromMinutes(20),
   CookiePath = "/",
});

If I click a link that causes the entire page to be loaded as a document response, however, the server properly extends the session.

Joannjoanna answered 16/10, 2015 at 21:7 Comment(6)
are you using session.abandon to kill session/logout? if so that is not correct way with OWIN. With OWIN you should use AuthenticationManager.SignOut methodHarlot
If you look at the response headers do you see things like no-cache set? If so you may be hitting a cookie conflict issue: katanaproject.codeplex.com/…Nachison
It might be worth cracking open fiddler and inspecting the requests/responses.Lodhia
How are you calling the ajax request? Be sure when you use jQuery to specify cache:false;Deflower
did you ever find answer to this?Siward
@Siward Check the answer I just posted.Joannjoanna
J
0

I ended up having some faulty assumptions. The AJAX requests were extending. The return of the 200 was throwing me off. After looking with fiddler at the actual response, I saw that with the change to OWIN, the 401 is actually moved in the response:

X-Responded-JSON: {"status":401,"headers":{...foo...}}

So, we ended up just setting the status of the response back to 401. That's probably horrible, but it fit our needs.

protected void Application_EndRequest() {
    var context = new HttpContextWrapper(Context);
    var header = context.Response.Headers["X-Responded-JSON"];
    if (header != null && header.Contains("\"status\":401")) {
        Context.Response.Clear();
        Context.Response.StatusCode = 401;
    }

Here's probably a more robust solution: OWIN: unauthorised webapi call returning login page rather than 401

Joannjoanna answered 21/1, 2016 at 22:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.