When you make a request after your login session has expired ASP.NET will automatically do a 302 redirect to your login action instead of returning a 401 "Unauthorized". The browser will quietly follow the redirect (even during an AJAX request) and make a second request to bring down the login page.
There's no way that I am aware of to detect or prevent this redirect in Javascript and there's no way of prevent the redirect server-side without reimplementing the entire FormsAuthenticationModule.
However, jQuery inserts an HTTP header
X-Requested-With=XmlHttpRequest
when making Ajax calls. The Request.IsAjaxRequest() method in ASP.NET MVC can be used to detect the presence of this header.
What we do in our site is put
if (Request.IsAjaxRequest()) {
return new HttpUnauthorizedResult();
}
into our /auth/login action so that a 401 error is returned instead of the login page HTML if /auth/login is called during an AJAX call. We then detect the 401 in Javascript and redirect to the login page manually.
Unfortunately Firefox (as of 3.5) and Opera (as of ~9.something) do not maintain the X-Requested-With header in the second request after a redirect, so IsAjaxRequest() returns false in this situation when these browsers are being used. This wasn't a big issue for us but its something to keep in mind.