Monday, June 27, 2016

How to return a 401 status code using ASP.NET MVC 5 and OWIN

This time I was trying to force users to the login page after an Ajax request failed because of an expired session. I was getting something like this in the response:

X-Responded-JSON: {"status":401,"headers":...
  
I investigated a little and turned out you have to add this code to your Startup.Auth.cs file:

Provider = new CookieAuthenticationProvider
{
  OnApplyRedirect = ctx =>
  {
    if (!IsAjaxRequest(ctx.Request))
    {
       ctx.Response.Redirect(ctx.RedirectUri);
    }
  }
}

Also, in your filter I suggest you do something like this:


if (filterContext.HttpContext.Request.IsAjaxRequest())
{
filterContext.HttpContext.Items["RequestWasNotAuthorized"] = true;
filterContext.HttpContext.Response.StatusCode = 401;
filterContext.HttpContext.Response.End();
filterContext.Result = new HttpUnauthorizedResult();
}


And then handle it in JavaScript like this:

$(document).ajaxError(function (xhr, props) {
if (props.status === 401) {
location.reload();
}
});


More information on the error can be found here:
http://kevin-junghans.blogspot.mx/2013/12/returning-401-http-status-code-on.html
https://brockallen.com/2013/10/27/using-cookie-authentication-middleware-with-web-api-and-401-response-codes/

Wednesday, June 15, 2016

A connection was successfully established with the server, but then an error occurred during the login process. (provider: Shared Memory Provider, error: 0 - The handle is invalid.)

The solution is simple, just reset IIS. If that doesn't work, this SO question will help

http://stackoverflow.com/questions/3270199/a-connection-was-successfully-established-with-the-server-but-then-an-error-occ