ASP.Net MVC: Handling Forms Authentication Timeouts for AJAX Requests
Posted over 2 years ago on September 26, 2010
Problem: You need a way to redirect the user back to a login page when a user makes an AJAX request and their forms authentication session has timed out.
Solution: Add a HTTP header onto each AJAX response that indicates whether or not the user is still logged in and their session is active.
This is an example of how you might add a response header to each AJAX request.
using System.Web.Mvc;
using System.Web.Security;
namespace MVCAjaxFormsAuthTimeout.Helper
{
public class CommunicateAuthStatusToAjaxClientAttribute : ActionFilterAttribute
{
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
if(filterContext.HttpContext.Request.IsAjaxRequest())
{
if(filterContext.HttpContext.User.Identity.IsAuthenticated)
filterContext.HttpContext.Response.Headers.Add("X_User_Logged_In", "true");
}
base.OnActionExecuted(filterContext);
}
}
}
Usage:
[CommunicateAuthStatusToAjaxClient]
public class HomeController : Controller
{
public ActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET MVC!";
return View();
}
}
On the client side, I want every AJAX request made from jQuery to check this header. Instead of touching every place where I make a call to the server, I use the ajaxSuccess(...) method to configure this once in the master page.
When the users' session has ended, the header variable will be empty and the alert and redirect will execute.
Note: Modifying response headers requires "IIS Integrated Pipeline Mode" which the Cassini development server does not support. Therefore, if you would like to see the code run you must configure IIS to handle the web project.