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