Development With A Dot

Blog on development in general, and specifically on .NET

Sponsors

News

My Friends

My Links

Permanent Posts

Portuguese Communities

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

Here’s what I did: first, I hooked an event listener to the completedRequest event of the Sys.Net.WebRequestManager JavaScript object, part of Microsoft’s AJAX Library. This event fires whenever an asynchronous call, made typically by an UpdatePanel, terminates.

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:

   1: Sys.Application.add_init
   2:     (
   3:         function ()
   4:         {
   5:             Sys.Net.WebRequestManager.add_completedRequest
   6:             (
   7:                 function (s, e)
   8:                 {
   9:                     if (s._xmlHttpRequest.responseText.indexOf('this is the login page') >= 0)
  10:                     {
  11:                         if (window.confirm('You are no longer authenticated. Do you wish to return to the login page?'))
  12:                         {   
  13:                             window.location.href = '/Login.aspx?ReturnURL=' + window.location.pathname;
  14:                         }
  15:                     }
  16:                 }
  17:             );
  18:         }
  19:     );

And that’s it. Just place this in your master page or on a control that goes on every page.

Comments

asp.net developers said:

Your Post is very interested and it is more useful and helpful for me to develop the .NET Applications. Thanks for sharing this valueable post.

# January 24, 2012 2:29 AM