How to fix ASP.NET FormsAuthentication redirecting to login page for unauthorized AJAX calls

This one stumped me for quite a few hours. I was working on a ASP.NET project where a user’s session was expiring while they were still on the page. Clicking a save button would make a (now unauthorized) ajax call to an endpoint which asp.net would automatically redirect (http 301) to the login page. In my case, the ajax function would then receive the raw html for the login page rather than an ajax friendly json response.

I originally went down the rabbit hole of attempting to write a custom AuthorizeAttribute and override HandleUnauthorizedRequest method but nothing was working. The solution I finally stumbled upon was to add a check on Application_EndRequest in Global.asax.cs for the following request properties:

  • FormsAuthentication is enabled
  • Response status code is 301
  • The Request is an ajax request
  • The Request is not authenticated

All put together, this looks something like:


protected void Application_EndRequest()
{
     var context = new HttpContextWrapper(this.Context);

     // If the request is an ajax request, results in a 302 and uses form authentication, return a status code of 401 rather than redirecting
     if (FormsAuthentication.IsEnabled && context.Response.StatusCode == (int)HttpStatusCode.Redirect &&
     context.Request.IsAjaxRequest() && !context.Request.IsAuthenticated)
     {
         context.Response.Clear();
         context.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
     }
}

Credit to this post for the solution.

Thanks for reading!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s