I recently received an email from a developer who needed to implement a behavior around a user’s session timeout behavior.
As you probably know, we can configure our application to “expire” a user’s session at any interval that we wish.
Example:
<system.web> <sessionState timeout="10" /> ........ </system.web>
We can add a specification to our application’s web.config file to change the default session expiration time from 20 minutes to a time span of our own choosing. (10 minutes in the example above.)
The session timeout value is a sliding value; on each request the timeout period is set to the current time plus the timeout value.
This means that if a user submits a request after the timeout period expires, the session will have been terminated and the user will no longer be authenticated. If the user’s “post-back” is requesting a secured resource, they will be redirected to the “login” page since the application sees this request as from an anonymous user. (When a session expires the user is de-authenticated.)
The problem in this cast is that the application requirements required that the user be AUTOMATICALLY redirected when the session times out.
This is a sound security practice in certain applications.
For example, lets suppose the application’s user has displayed the results of a query of “sensitive” information. If the user then walks away from their PC, that sensitive data will stay displayed indefinably.
The application that I was contacted about needed the user’s browser to be automatically be redirected when the session timed out.
The problem, of course, is that browser based applications are innately stateless sine they run on HTTP ( a stateless protocol). The browser (client) and the sever only communicate when the CLIENT specifically makes a request of the server.
To meet the applications requirements we can add a timer in JavaScript to be run in the browser.
In our master page (so that the JavaScript will be included in, and executed by every page in our application) we can include the following client side script:
1: <head runat="server">
2: <title></title>
3: <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
4: <script type="text/javascript" language="javascript">
5: <!--
6: var secs
7: var timerID = null
8: var timerRunning = false
9: var delay = 1000
10:
11: function InitializeTimer()
12: {
13: if (typeof HeadLoginName != 'undefined') {
14: // Set the length of the timer, in seconds
15: secs = 630
16: StopTheClock()
17: StartTheTimer()
18: }
19: }
20:
21: function StopTheClock()
22: {
23: if (timerRunning)
24: clearTimeout(timerID)
25: timerRunning = false
26: }
27:
28: function StartTheTimer()
29: {
30: if (secs == 0)
31: {
32: StopTheClock()
33: window.location = "default.aspx"
34: }
35: else
36: {
37: self.status = secs
38: secs = secs - 1
39: timerRunning = true
40: timerID = self.setTimeout("StartTheTimer()", delay)
41: }
42: }
43: //-->
44: </script>
45:
46: <asp:ContentPlaceHolder ID="HeadContent" runat="server">
47: </asp:ContentPlaceHolder>
48: </head>
Then we add an “onload” to our html body tag as so:
<body onload="InitializeTimer()">
Note that the client side timer is set to 10 minutes and 30 seconds. This is a plus 30 second complement to the server side setting of 10 minutes so that we should be sure that when the client code “times out” the session on the server will have already expired.
When the client side timer counts down to zero this line of JavaScript code:
33: window.location = "default.aspx"
causes the browser to request the application’s default page.
We could, of course, just post back to the “current” page and let the application’s authentication configuration redirect the user to the application’s login page.
Note that this method is a loose synchronization of the applications session. If we absolutely needed an exact synchronization we could implement an AJAX service method and query the server as to whether or not the REAL .NET session has expired, but we’re not going to do that here since it creates some unnecessary (for most applications) http traffic.
We could of course do other things form our client side code and do things like black the browser window and pop up a dialog (like a screen saver) or really whatever we want. jQuery is great for this kind of powerful client side work.
Here is a quick bit of sample code that shows the technique – [ DOWNLOAD HERE ].





















RE: Session Time Out Tricks
Pingback from Session Time Out Tricks : Misfit Geek
Thank you very much
RE: Session Time Out Tricks
Session Time Out Tricks msjoe.com/…/session-time-ou #asp .net
Is it just me, or is this not overkill? Why not just use the <meta tag with a refresh attribute set, and print this out with the Session.Timeout property + 30. Your solution is a lot of code, and won’t work if the browser has JavaScript disabled (not a huge issue these days, but still something to bear in mind!).
For example:
<META HTTP-EQUIV="REFRESH" CONTENT="1020; URL=LoggedOut.aspx">
thanks a lot, I have faced a lot of problem on session timeout issue
Hi,
Very very thanks for your tricks Session time out tutorial code. I am beginner about programming language but high experience advance user knowledge. Please I want more code for tech my self. I am OSI Upper Layer with lower Layer Programming interested. Long distance learning solution. I/we always remember you internal mind also MSDN. %100 Success.
Take care.
Sincereley, Foysal.
Thanks very much, it was very helpful info.
best regards
Nice post, thanks a lot.
How do you handle async / web service calls that make keep the session alive without causing your script to reload?
I’m with Matt, complete overkill. Use the global.asax to insert a meta tag to the user’s browser. You can dynamically specify the content value based on the sessions time out value. All of this can be done with 3 lines of managed code.
Very interesting, I will try
how about good old fashioned Meta tag trick for HTTP sessions
<meta http-equiv="REFRESH" content="20;url=http://www.the-domain-you-want-to-redirect-to.com"> is the part that actually does the redirecting.
The number preceding the url (in this case 20) tells the browser the number of seconds to wait before redirecting to the new url.
SIR , CAN U PLEASE HELP ME BY SHOWING HOW TO SEND SMS TROUGH ASP.NET,
I ASK FOR UR KIND HELP ME WITH THAT .
I WANT TO IMPLEMENT SENDING SMS THROUGH ASP.NET
RE: Session Time Out Tricks
Linked – List
>> we could implement an AJAX service method and query the server as to whether or not the REAL .NET session has expired
Would this request reset the timeout value?
looking very interesting. i ll try….
Very thanks for your tricks! Its Cool Man!
Good job man!
Excellent. Two ideas for the price of one. I like the Javascript and the Metadata.
Saw in some websites a pop-up window opens warning you that your session is about to expire, and you can click on ‘continue logged in’. This is good use of the javascript code.
Riga
Hi Joe,
Nice article. I did something like this recently using MVC and jQuery. If you like you can check it out.
http://www.dotnetcurry.com/…/ShowArticle.asp
Hi,
I totally agree with Matt, Aaron and vineet … it is an overkill. Meta tag Refresh will do the job.
Nice article!
Thankx for the tip!
tuganologia.blogspot.com
@ Joe Stagner
I think you are mixing Session with Authentication. They are separate; but, you state, "the session will have been terminated and the user will no longer be authenticated". That will only be true if session *and* authentication have expired. Right?
Making it worse, FormsAuthentication.SlidingExpiration works differently than Session Sliding Expiration. "Sliding expiration resets the expiration time for a valid authentication cookie if a request is made and more than half of the timeout interval has elapsed. If the cookie expires, the user must re-authenticate."
msdn.microsoft.com/…/system.web.secu
@Matt, Aaron, vineet, and Nuno:
I think your approaches are oversimplified for a rich Web application. You are saying that it is okay for your user to lose data, because they can just start over. If you were the user of that app, you would/should be complaining.
There are mutlple solutions to each problem. For the orrigional request this solved their problem. The user’s requirements did not care about a "partially" entered form.
Feel free to write and post a solution you like better
I agree with Lee. Most applications that I develop (and I suspect many others) nowadays use AJAX (no postback), so as far as I know, the "old fashioned meta refresh" would not help me in this case. I’ve mostly been using the javascript method similar to what Joe suggests.
A related requirement from our customers and perhaps more useful to the end users is that they require 2 minutes before the session time out, warn the user and such they can extend the session. It’s used in a lot Bank websites.
I asked the question on ASP.NET forum and later resolved it. No ajax required either. Just server mix of Javascript + Server side coding
forums.asp.net/…/1207721.aspx
hope it helps
Thanks GUYSSSS
Session time out is a plage….I currently have no user authentication on my sites becuase of this. I’ll try to implement this workaround.
Nice trick and helpful.