Geeks With Blogs

News Awarded Microsoft MVP C#.NET - 2007, 2008 and 2009


I am born in Bangladesh and currently live in Melbourne, Australia. I am a Microsoft Certified Application Developer MCAD Chartered Member (C# .Net)and born in Bangladesh.
I am founder and Chief Executive Officer of
Simplexhub, a highly experienced software development company based in Melbourne Australia and Dhaka, Bangladesh. Co-founder and core developer of Pageflakes www.pageflakes.com.
Simplexhub, is on its mission to build a smart virtual community in Bangladesh and recently launched beta realestatebazaar.com.bd an ASP.NET MVC application written in C#.NET.


Some of My Articles
Flexible and Plugin based .Net Application..
Mass Emailing Functionality with C#, .NET 2.0, and Microsoft® SQL Server 2005 Service Broker'
Write your own Code Generator or Template Engine in .NET
Shahed Khan blog

Problem
Redirect the user to login page after a period of inactivity or when the session expires.

Investigation
A quick search on Google will find many articles which discuss how we can detect session expiration and how to redirect to the login page. However, most of the methods described require page refreshes or requests to the server to find out whether the session expired.

Some ways of detecting whether a session has expired:

1. ASP.NET Forum Article
If you are using cookie, you can store a marker in your cookie so you can tell the difference between "fresh browser + new session" and "old browser + expired session". Below is sample code that will redirect the user to an expired page if the session has expired.

void Session_OnStart(Object sender, EventArgs e)
{
  HttpContext context = HttpContext.Current;
  HttpCookieCollection cookies = context.Request.Cookies;
  if (cookies["starttime"] == null) {
    HttpCookie cookie = new HttpCookie("starttime", DateTime.Now.ToString());
    cookie.Path = "/";
    context.Response.Cookies.Add(cookie); 
  }
  else {
    context.Response.Redirect("expired.aspx");
  }
}
souce: http://forums.asp.net/p/7504/7504.aspx

2. ASP Alliance Article

The ASP.NET HttpSessionState class provides a useful IsNewSession( ) method that returns true if a new session was created for this request.  The key to detecting a session timeout is to also look for the ASP.NET_SessionId cookie in the request.  If this is a new session but the cookie is present, this indicates a timeout situation. 

basePageSessionExpire.cs

 public class basePageSessionExpire : System.Web.UI.Page
 {
    public basePageSessionExpire()
    {
    }

  override protected void OnInit(EventArgs e)
  {
       base.OnInit(e);


   //It appears from testing that the Request and Response both share the 
   // same cookie collection.  If I set a cookie myself in the Reponse, it is 
   // also immediately visible to the Request collection.  This just means that 
   // since the ASP.Net_SessionID is set in the Session HTTPModule (which 
   // has already run), thatwe can't use our own code to see if the cookie was 
   // actually sent by the agent with the request using the collection. Check if 
   // the given page supports session or not (this tested as reliable indicator 
   // if EnableSessionState is true), should not care about a page that does 
   // not need session
   if (Context.Session != null)
   {
    //Tested and the IsNewSession is more advanced then simply checking if 
   // a cookie is present, it does take into account a session timeout, because 
   // I tested a timeout and it did show as a new session
    if (Session.IsNewSession)
    {
     // If it says it is a new session, but an existing cookie exists, then it must 
   // have timed out (can't use the cookie collection because even on first 
   // request it already contains the cookie (request and response
     // seem to share the collection)
     string szCookieHeader = Request.Headers["Cookie"];
     if ((null != szCookieHeader) && (szCookieHeader.IndexOf("ASP.NET_SessionId") >= 0))
     {
      Response.Redirect("sessionTimeout.htm");
     }  
    } 
   }
  }
}

sessionTimeout.htm

source: http://aspalliance.com/520_Detecting_ASPNET_Session_Timeouts.2


MSDN Forum Discussion

if(Session["Session_name"]==null)

Response.Redirect("Login.aspx");

source: http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=1677554&SiteID=1

etc. etc a lot more out there....

Alternative Solution

Most of the methods suggested did not solve my problem as it required a request to be made to figure out whether the session has expired.

As the page served is stateless, it has no way to know whether the session in the server has expired until the page is refreshed/posted back.

The server session will time out after the period specified in the web.config, but it cannot auto-redirect the page on the client browser as the session has ended. Rather, the session can be programatically ended (using javascript) after a predetermined amount of time has elapsed.

What we can do is we can use an internal timer (javascript/ajax) that keeps track of the time since the last page request. In addition we need to know the Session Timeout value, and when the Session expiration time is reached we can programatically call Session.Abandon() and redirect to the Login page.

To implement this I had to create the following (ASP.NET 1.1):

BasePage.cs : This page has the capability to inject the javascript that will keep track of the time since the last page request, and when the session expiration time is reached, it redirects to logout.aspx. BasePage should be inherited by all pages that are required to be redirected.

public class BasePage : System.Web.UI.Page
{
  public SecurityApplicationPageBase()
  {
    this.Load += new System.EventHandler(this.Page_Load);
  }

  private void Page_Load(object sender, System.EventArgs e)
  {

    if(Session["Session_name"]==null) 
    {
      Response.Redirect("Login.aspx");
    }
    InjectSessionExpireScript();    
  }

  // For  demo purpose the timeout is set to a smaller value. 
  //Remember The Javascript setTimeout works in milliseconds. 
  protected void InjectSessionExpireScript( )
  {
    string script = "<script> \n" +
    "function expireSession(){ \n"+
    " window.location = '"+"Logout.aspx"+"'}\n"+
    "setTimeout('expireSession()', " +this.Session.Timeout * 1000 +" ); \n"+
    "</script>"
    this.Page.RegisterClientScriptBlock("expirescript",script);
  } 
}

Logout Page: This page calls Session.Abandon() and redirects to the login.aspx page.

public class LogOut : BasePage
{
  private void Page_Load(object sender, System.EventArgs e)
  {
       Session.Abandon();
       Response.Redirect("Login.aspx",true); 
  }
}

Login Page: This page facilitates login. On a successful login a Session variable is created.

public class LogIn : System.Web.UI.Page
{

  private void btnLogin_Click(object sender, System.EventArgs e)
  {
    //when username and pasword is correct
    Session.Add("Session_name","loggedinsuccessfully");
  }
}

SomeOtherPage: Inherits BasePage. After a certain period of inactivity, this redirects to the logout page.

public class SomeOtherPage : BasePage
{
}

Rendered HTML
<HTML>
<HEAD>
</HEAD>
<BODY>
.......
<script>
function expireSession(){
window.location='Logout.aspx'}
setTimeout('expireSession()',20000);//20 sec
</script>
<div>some other page</div>

.....
</BODY>
</HTML>

Conclusion
As the page that is served is stateless, we cannot know whether the Session has really expired without sending a page request back to the server. What we did here is we used an internal timer (javascript) that keeps track of the time since the last page request. By knowing the the Session Timeout value we set a delay period and when the Session expiration time is reached we called Session.Abandon() and then the user is redirected to the Login page.

Posted on Wednesday, September 5, 2007 12:54 PM | Back to top


Comments on this post: Redirect to Login page on session expiration (ASP.NET)

# re: Redirect to Login page on session expiration (ASP.NET)
Requesting Gravatar...
Do you think that your second sample "2. ASP Alliance Article" will work in an asynchronous web service?
Left by Roxane on Sep 26, 2007 9:43 AM

# re: Redirect to Login page on session expiration (ASP.NET)
Requesting Gravatar...
alternative solution for redirection page is excellent.... but need to used as shared function or method ... if it shared then only we need not to write in multiple pages of our sites.. am i right.... tha javscript function needs to be shared...
Left by ibrahim on Jan 05, 2008 12:06 AM

# re: Redirect to Login page on session expiration (ASP.NET)
Requesting Gravatar...
Hi ,

Can u give some lights on this scenario, My application working fine at the client system but some times it redirect to the login page i increased the session timeout also but can detect what the problem is,

Application is works fine for most of the system. We have also a support group in that group we find this problem one in a mont h from 1 of the 82 countries. and in some time it also happes with our testing server also but we are unable to detect,what should i do.

I thought may be it is happening due to errors say a error come and it is handled in the try catch block but the due to rasing the exception our session vanished.

CONFUSED?????????
Left by Pradeep bisht on Apr 08, 2008 6:08 PM

# re: Redirect to Login page on session expiration (ASP.NET)
Requesting Gravatar...
Hi..
im using session variables to store the login information of the user..
When user login and logout he cant review the pages he visited, its working fine ...

but if another user login's he can see all the pages visited by the previous user by clicking back button. Since session ID is not null it allows the page to appear..

Can u tell me how to remove all browser list on Logout..

thanks in advance
Left by vinay k on Apr 14, 2008 1:22 AM

# re: Redirect to Login page on session expiration (ASP.NET)
Requesting Gravatar...
There is no need to inject JavaScript to perform the auto-redirection. You can just put a refresh command into your HTTP headers and it will perform the same function. It's simpler, less code, and will work even if the user has javascript disabled. There's no chance of a javascript error causing your auto-redirection functionality from not working.

You can put this into your BasePage to achieve the same result sans JavaScript:

//The following line makes the browser auto-redirect to the timeout page
//after the session timeout value.
Context.Response.AppendHeader("Refresh",
Convert.ToString(Session.Timeout * 60) + "; URL=" + TIMEOUT_URL);
Left by rlively on Jun 05, 2008 5:07 AM

# re: Redirect to Login page on session expiration (ASP.NET)
Requesting Gravatar...
See the W3C (World Wide Web Consortium) page on this topic at http://www.w3.org/QA/Tips/reback.

The W3C article is comparing META refreshes to a HTTP header refreshes, but the same comparisons apply to the JavaScript vs HTTP header methods, as the JavaScript method is still in client-side code embedded in the document. In addition, JavaScript method also encompasses additional drawbacks that even the META tag method does not posess.

From Wikipedia on redirects:

http://en.wikipedia.org/wiki/URL_redirection#JavaScript_redirects

JavaScript redirects

JavaScript offers several ways to display a different page in the current browser window. Quite frequently, they are used for a redirect. However, there are several reasons to prefer HTTP header or the refresh meta tag (whenever it is possible) over JavaScript redirects:
There are several reasons for some users to disable JavaScript:
Security considerations
Some browsers don't support JavaScript
many crawlers (e.g. from search engines) don't execute JavaScript.
There is no "standard" way of doing it: A search for "you are being redirected" will find that virtually each JavaScript redirect employs different methods. This makes it difficult for Web client programmers to honor your redirect request without implementing all of JavaScript.
Left by rlively on Jun 05, 2008 5:22 AM

# Redirect to Login page on session expiration (ASP.NET)
Requesting Gravatar...
Hi Shahed,

I am new in ASP.NET. please help me.

i making login page. after sign out, when i click the "Back Button" from toolbal then page is showing the previous page.

thanks
Ved prakash


Left by Ved Prakash on Jun 05, 2008 6:29 PM

# re: Redirect to Login page on session expiration (ASP.NET)
Requesting Gravatar...
thanx but line 11 error
Left by porno video on Jun 07, 2008 9:12 AM

# re: Redirect to Login page on session expiration (ASP.NET)
Requesting Gravatar...
i m developing web application in which m creating session expire on timeout with webconfig and global.asax.
in web config i m writting code like
<sessionState mode ="InProc" cookieless ="false" timeout ="1"></sessionState>
and in global.asax the session end event is
protected void Session_End(object sender, EventArgs e)
{
Session.Abandon();
Response.Redirect("Login.aspx",true);
}
it triger session_end on 1 minute but it does not redirect on login.aspx and go inot application_error event of global.asax.
i want to redirect on login page. pls help me. tell where m wrong..

thanks in advance.
From,
Pramit.
Left by Pramit on Mar 15, 2009 12:41 AM

# re: Redirect to Login page on session expiration (ASP.NET)
Requesting Gravatar...
It's works
Left by Wander on Jul 11, 2009 4:23 AM

Your comment:
 (will show your gravatar)


Copyright © Shahed Khan | Powered by: GeeksWithBlogs.net