Click to search the site Click to log in
Online articles
Download free tools
Support pages, per product
Services
Frequently asked questions, per product
Handling session and authentication timeouts in ASP.Net
Author: George Mihaescu
Published: February 15, 2007
Category: Implementation technique / ASP.Net 2.0
Notes: Tested with Firefox 1.x, 2.0 and IE 6 and 7
Description: This article describes the handling of in-process session and authentication timeouts in an ASP.Net application. Both types of timeouts are discussed in the same article because sometimes there may be a dependency between the two. The article also covers the in-process session timeout due to application domain recycling and the conditions that can cause the recycling. Applies to ASP.Net 2.0 (I have not tested the solutions listed here on ASP.Net 1.1 or 1.0).
View count: 362,634
Comments: 22 Read comments or post your own

  Print viewOpens in new window
 Handling session and authentication timeouts in ASP

Handling session and authentication timeouts in ASP.Net

 

By George Mihaescu

 

Summary: this article describes the handling of in-process session and authentication timeouts in an ASP.Net application. Both types of timeouts are discussed in the same article because sometimes there may be a dependency between the two. The article also covers the in-process session timeout due to application domain recycling and the conditions that can cause the recycling. Applies to ASP.Net 2.0 (I have not tested the solutions listed here on ASP.Net 1.1 or 1.0).

Handling the in-process session timeout

You configure your session's attributes (including the timeout) through the web.config file, similar to:

 

<sessionState cookieless="UseDeviceProfile" timeout="30" />

 

This specifies that a user's in-process session will expire after 30 minutes of inactivity (i.e. no requests received from that user in the specified time since the last request). When the timeout occurs, the session in question is destroyed and any data that you had stored for that user in the session is therefore gone.

 

Many developers forget about this possibility and assume that once they've stuck something in the session, it will be forever there. However, if the user hits the site again after his previous session has expired, ASP.Net will create a new session for him, one that obviously will be initially empty. This means that the following scenario is possible: the user accesses the site, has a session and goes through a number of pages that cause some data to be accumulated in the session, but then makes no requests for more than your set timeout, causing the session to expire on the server. Then the user gets back to the browser and hits submit in the page he has in the browser – if your code assumes the data to be in the session and work with it, you are in trouble.

The immediate solution that comes to mind is to always check whether the expected data is in the session, and if not, redirect the user to a page where he can start the input again, a page where no data is expected to be in the session (for example, the home page, showing an explanation that the user's session has expired due to inactivity). However, this solution is not robust enough, especially for large applications, with many developers involved because:

  • I can easily imagine some developers forgetting to check the returned object from the session and assuming it is there. This is basically the equivalent of not checking a function's return code, something which is not detected by any tools that I know of, and which is also difficult to test (what are you going to do? Sit in front of each page and wait for the session to expire then hit every possible postback action in the page?)
  • Certain objects may be missing in the session for good reasons (i.e. it is an accepted business rule), and this only confuses the "always check the object retrieved from the session" rule. The developer must now know what might be rightly missing from the session and what actually should be there, but if not, conclude the session has expired and handle this case.

 

Therefore, you'd need a more robust and ideally, centralized mechanism to detect a user's session expiration and redirect the user to the said "start" page when he can go through the motions without crashing because the session is now empty.

 

 

The solution I found for this is to use the global Session_Start method in global.asax. This method is called in the context of a user's request, when the user's session is created. The trick is to detect whether this user had a previous session on the server – if he did, the fact that a new session is being created for him means that the previous one had timed out. The way to detect that the user had a previous session on the server is to look in the request headers for the session ID cookie:

 

void Session_Start(object sender, EventArgs e)

{

    //This is obviously a new session being created; it can be

    //created at the first hit of a user, or when the user

    //previous session has expired (timeout). We are only interested

    //in the timeout scenario, so we look at the request cookies

    //and if we have a previous session ID cookie, it means this is a

    //new session due to the timing out of the old one.

    //Note: slight problem here: in .Net 2.0 the ASP Session ID

    //cookie name is configurable, but we don't have a way to

    //retrieve that from the web.config - so if you customize

    //the session cookie name in the web.config you'll have to

    //use the same name here.

    string request_cookies = Request.Headers["Cookie"];

    if ((null != request_cookies) &&

            (request_cookies.IndexOf("ASP.NET_SessionId") >= 0))

    {

        //cookie existed, so this new one is due to timeout.

        //Redirect the user to the login page

        System.Diagnostics.Debug.WriteLine("Session expired!");

        Response.Redirect(Constants.HOME_PAGE + "?" +

                          Constants.PARAM_REQUEST + "=" +

                          Constants.PARAM_REQUEST_VALUE_TIMEOUT);

    }

}

 

The default name of the ASP.Net session cookie is "ASP.NET_SessionId". Note that (as the comments in the code explain) there is a small potential problem here, as starting with ASP.Net 2.0 the name of the ASP.Net session cookie is configurable in the web.config, but there is no way of programmatically retrieving that custom name – so if you do specify a custom ASP.Net session cookie name, you're stuck to hard-coding the same name in the code above, and keeping the two in sync.

 

The mechanism presented above worked flawlessly for me in several sites; it has the great advantages of being simple and centralized, thus guaranteeing that the moment the user hits any page after his session has expired, he is automatically sent to a location where he can safely start.

 

Note that the session may expire not only because of the user timing out; something developers often forget is that all the user sessions will also expire when the application domain is being recycled by the ASP.Net hosting process. The conditions under which the app domain is recycled are discussed at the end of this article.

Handling the authentication timeout

If you are using ASP.Net forms authentication you must configure the authentication in the web.config in a manner similar to this:

 

<authentication mode="Forms">

  <forms    name="MyAuthCookie"

loginUrl="login.aspx "

defaultUrl="home.aspx"

timeout="40"

            slidingExpiration="true"

cookieless="UseDeviceProfile"

path="/"

protection="All" />

</authentication>

 

The timeout attribute specifies the period in minutes after which the authentication token (cookie) will expire; the reference is the time the token was issued (if slidingExpiration is false – which is the default in ASP.Net 2.) or the last request time (if slidingExpiration is true; which is the default in ASP.Net 1.x).

 

Handling the authentication timeout is basically done automatically by ASP.Net: when the timeout occurs, any page that has restricted access (as specified in web.config) will cause the user to be redirected to the page specified in the loginURL attribute. So there isn't a lot to be said about this. However, you must pay attention to the case when the session expires before the authentication; you may be left with an authenticated user that does not have a session anymore. If you don't store anything related to the user security privileges in the session – for instance, his role / access rights - this is not an issue (after all, you can handle this as described above for the session timeout case).

But if you do, then the session handling will not help you, because you are left with an authenticated user for which you don't know the security privileges anymore.

 

This is why I recommend that generally you don’t store such security-related attributes in the session. If you do, then you must handle the session timeout as a logout, and force the user to log in again. This, however, is not handled automatically by ASP.Net and you will have to do it yourself.

Do you have a dependency between the user's authentication token and his session?

Ideally, the answer should be no. You should not rely on the session data being available for security-related issues for many reasons, among others being the separation of concerns. One token deals with user access rights, the other with storing user data across requests. However, in many cases developers choose to store the user's access rights in the session, most often in sites that allow both anonymous and authenticated access, with authenticated users having more functions / pages available to them then the anonymous ones. So instead of storing an access rights token in the user's authentication cookie, developers choose to store the user's access rights in the user's session (sometimes because of what is perceived to be a security issue – however, this is a generally a false concern, as the user's authentication token can be encrypted very strongly an very easily through the protection attribute of the forms element in web.config). But this assumes that the session does not expire before the authentication – otherwise you would be left with an authenticated user for which you actually don't know the access rights, as those were stored in the session that is now gone. When faced with this dependency, many developers think it will suffice to set the session timeout to a higher value than the authentication timeout, and set the slidingExpiration to true for the forms authentication. The thinking is that in this setup the user authentication will expire first, causing the ASP.Net to automatically handle this and redirect the user to the login page (as set in the web.config). If the session is still around, it will be renewed, if not, a new one will be created and then the user's access rights will be set as per his login.

 

But the above logic does not always work: even with the setup described, there is always the possibility that the user's session expires before the authentication token, due to application domain recycling. When this happens, all the user sessions are terminated, so all authenticated users will be left without the related data in the session. In other words, if you do store authentication-related data in the user's session, you must always handle the case when the session expires before the authentication token, regardless of your timeout settings. The section below describes the conditions under which the application domain is recycled.

Session termination due to app domain recycling

In ASP.Net each application resides in its application domain. Essentially an application domain is for the ASP.Net runtime host what a process is for the operating system: the ASP.Net runtime host can run multiple application domains, each in its separate memory space, with its own security attributes, loaded assemblies, etc. The sole purpose of the application domain is to provide isolation (memory, security, etc) to .Net applications running under the same runtime host.
The ASP.Net runtime host has the ability to recycle any app domain it is running, meaning that the app domain is destroyed and re-created (all assemblies are reloaded, the code is re-jitted, all the in-process variables – such as Cache and Session are destroyed, etc). Obviously, besides killing all the sessions, an app domain recycle will also cause a major performance hit to your application.

 

The ASP.Net runtime host will recycle an app domain under the following conditions:

1.    The web service is restarted – an obvious one, so I won't comment any further on this.

2.    Global.asax is modified – another obvious one, again I won't comment.

3.    Machine.config or web.config are modified – again, those appear to be obvious reasons to recycle the app domain, but in many cases those are in fact not modified explicitly – they could simply be "touched" by another program, such as a an anti-virus program. To avoid unexpected recycles, set up such programs to exclude those files from their periodic scan.

4.    The contents of the bin directory is modified – again, those can be changes that are not done explicitly, but caused by another program touching the files. As above, make sure that an anti-virus or similar program excludes the files in the bin directory from the scan.

5.    The number of re-compilations of aspx, ascx or asax exceeds the threshold set by <compilation numRecompilesBeforeAppRestart=/> in machine.config or web.config  (the default is 15).

6.    The physical path of the IIS virtual directory is modified.

7.    Sub-directories are deleted or renamed. This is new to ASP.Net 2.0 and (in my opinion) a very aggressive policy. Whenever you delete or rename a sub-directory of your application, the application domain is recycled, terminating all users' sessions (and the cache, etc). Besides being a big performance hit, this behavior affects dramatically sites that allow document publishing, to the point where they stop functioning. Imagine a situation where a request creates a thread that goes through sub-directories of the application and deletes / renames them – without knowing about this 2.0 application domain recycling policy, chances are that the worker thread in question will not complete because the domain is recycled and the thread aborted. Currently I don't know any way of altering this behavior; the only solution I have is to locate any content that needs to have the directory names altered outside the application's root directory.

 

If you suspect app domain restarts (meaning: your sessions seem to expire without obvious reasons), you will be interested to know when the restarts happen and what's causing them. One simple way of doing this (again, available only in .Net 2.0) is to add the following element to the global web.config file (under C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\CONFIG) as a child of the <healthMonitoring><rules> elements:

 

<add name="Application Lifetime Events Default"

eventName="Application Lifetime Events"

      provider="EventLogProvider"

profile="Default"

minInstances="1"

      maxLimit="Infinite"

minInterval="00:01:00"

custom="" />

 

This will log system events that provide the time and the reason of the restart (such as: Application is shutting down. Reason: Configuration changed.)

 


Reader comments:
Name: (optional)
Verification text:    
(type as in image next to it)
Comment: max 2,000 characters; for security reasons no active content / no HTML formatting is supported.
Please stick to the subject of the article; comments are reviewed and unrelated / inappropriate ones will be deleted.

On Jan 24, 2014 at 5:35 EST http://www.abstraction.net/GetCaptchaImage.aspx said:

*** The comment was removed due to unrelated or inappropriate content. ***

On Aug 4, 2013 at 20:07 EST xifgvxyusn said:

*** The comment was removed due to unrelated or inappropriate content. ***

On Aug 1, 2013 at 22:35 EST hvlcwmzdve said:

*** The comment was removed due to unrelated or inappropriate content. ***

On Jul 31, 2013 at 1:04 EST dxtejzwjke said:

*** The comment was removed due to unrelated or inappropriate content. ***

On Jul 30, 2013 at 12:01 EST nzfwlgjtty said:

*** The comment was removed due to unrelated or inappropriate content. ***

On Jul 28, 2013 at 6:48 EST ukdvgculwq said:

*** The comment was removed due to unrelated or inappropriate content. ***

On Mar 25, 2012 at 9:26 EST Gianpiero said:

*** The comment was removed due to unrelated or inappropriate content. ***

On Mar 25, 2012 at 9:25 EST Gianpiero said:

*** The comment was removed due to unrelated or inappropriate content. ***

On Sep 28, 2011 at 1:18 EST Nitin said:

Great work!!! Keep posting

On Dec 15, 2010 at 14:33 EST Sean said:

In your Session_Start example, instead of checking for a previous auth cookie in the request, couldn't one simply check Context.Request.IsAuthenticated?

On Nov 14, 2010 at 13:50 EST Will S said:

This is the BEST overview I have found of this issue. I'm shocked that it is not covered better in the myriad of ASP.Net books I've been reading or in the MSDN docs on these features. Thank you very much.

On Mar 20, 2010 at 23:42 EST Ranjit Nair said:

one of the best article on session time out, it has reduced my work on handling sessions considerably. Thank you so much and keep posting !!!

On Jan 20, 2010 at 15:29 EST Troner said:

Best article ever! No other forum anywhere on the internet has anyone explained this nagging issue of Session_End not firing thoroughly. Not only did you provide the possible reasons why this could happen but you also provided for a way to monitor when and why it is happening. Kudos to you George!

On Dec 23, 2009 at 19:25 EST TJO said:

This article explains my error: http://mvolo.com/blogs/serverside/archive/2007/11/10/Integrated-mode-Request-is-not-available-in-this-context-in-Application_5F00_Start.aspx

On Dec 23, 2009 at 19:17 EST TJO` said:

Getting Error: "Request is not available in this context " Line 5: void Application_Start(object sender, EventArgs e) Line 6: { Line 7: string request_cookies = Request.Headers["Cookie"]; Line 8: if ((null != request_cookies) && Line 9: (request_cookies.IndexOf("ASP.NET_SessionId") >= 0))

On Nov 20, 2009 at 16:28 EST George said:

Thanks for the kind words Ernst. So if I understood you correctly, what you want is to avoid sending the user to the "start" page if he was not logged in when the session expires, because in this case you don't need to restore any state in the session. Session expiration means nothing in this case (i.e. you don't need to do anything). Although you could easily get the page the user is coming from when the session expired (Request.UrlReferrer) but I would not base it on that because: a) where the user is coming from should have no bearing on how you handle the rebuilding of his session. b) what are you going to do, compare it with each page that allows anonymous access (if you have more than such 3 pages that code would look pretty ugly, and then every time you'd add a new page that allows anonymous access you have to remember to add it to this check) c) what if the user WAS logged in, but then navigated to a page that allows anonymous access, after which his session expires? You would check the page he's coming from: it'a a "public" one, therefore don't redirect him to "start" - which is wrong, because the user was in fact authenticated. You should base this check on the authentication cookie being present in the request or not. Look in the Request for the authentication cookie: if there, user was authenticated (regardless where what page he was when the session expired) so you need to send him to "start". If cookie not there, user was not authenticated, you don't need to do anything to handle the session expiration. Hope this helps.

On Nov 19, 2009 at 8:21 EST Ernst Geyser said:

Hi George, This article has been most helpfull, thanx. However, is there any way once established that the session has timed out, what page the user was on prior to timeout as there are some pages the user can access without loging in? I only use session variables after the user has logged in and thus would want to ignore session expiration if the user has not yet logged in.

On Mar 23, 2009 at 17:30 EST George said:

Suresh, Constants is just a static class where I put my constants... The above is an example, you should not expect that you copy & paste things and they work just like that, especially if you don't understand how they work. I'm trying to explain things that worked for me, as MECHANISMS, not to give you some code to blindly paste into your app and have it work.

On Mar 9, 2009 at 5:41 EST Suresh said:

I could not figure out 'Constants' please help me

On Feb 6, 2009 at 7:10 EST Anonymous said:

I could not figure out what is Constants Response.Redirect(Constants.HOME_PAGE + "?" +...... could you please help me out, in which namespace does it belongs?

On Aug 27, 2008 at 8:03 EST Zouren Freeyan said:

Good Tips for keeping in mind. Like your writing style, very easy and understanding. Thank you.

On Apr 17, 2007 at 16:45 EST Scott said:

Thanks for another good article. I especially liked the description of the interplay between the session and authentication timeouts (something I guess few people think about, because application recycling by the ASP worker process is not at the top of your things to keep in mind).
Copyright 14,082 registered users, 52 users online now