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))

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.Result = new HttpUnauthorizedResult();

And then handle it in JavaScript like this:

$(document).ajaxError(function (xhr, props) {
if (props.status === 401) {

More information on the error can be found here:

No comments: