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/
No comments:
Post a Comment