Detecting Authentication Expiration in ASP.NET
I recently had to solve a problem: when issuing an asynchronous call by using an UpdatePanel, if the user is no longer authenticated – due possibly to long inactivity – this situation is silently ignored. What happens is, when an unauthenticated user tries to access a protected resource, ASP.NET redirects the request to the login page, and still returns a 302 HTTP status code (Found).
Inside it, I look at the response text, directly at the XMLHttpRequest instance. If it contains a text that I know only my login page contains (a comment inside <!-- -->, such as <!—this is the login page -->), then I know I am no longer authenticated, since my async requests are getting redirected.
All I can do at this point is give the user the option to authenticate again, by redirecting to the login page (yes, I know about application services, but that is not the point here).
So, here’s the code:
3: function ()
7: function (s, e)
9: if (s._xmlHttpRequest.responseText.indexOf('this is the login page') >= 0)
11: if (window.confirm('You are no longer authenticated. Do you wish to return to the login page?'))
13: window.location.href = '/Login.aspx?ReturnURL=' + window.location.pathname;
And that’s it. Just place this in your master page or on a control that goes on every page.