posts - 218, comments - 222, trackbacks - 68

My Links

News




I am a Microsoft Certified Application Developer MCAD Chartered Member (C# .Net) and born in Bangladesh.
I work for Ocean Informatics Pty Ltd as a Senior Developer - Analyst.
I am also co-founder and core developer of Pageflakes (acquired by LiveUniverse) www.pageflakes.com
and most recently created SmartCodeGenerator

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
Smart Code Generator .NET: Usage Overview
Smart Code Generator .NET: Architectural Overview
Smart Code Generator .NET: using with NAnt and Cassini

Archives

Free Programming Language Training

Redirect to Login page on session expiration (ASP.NET)

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.

Print | posted on Wednesday, September 05, 2007 12:54 PM |

Feedback

Gravatar

# re: Redirect to Login page on session expiration (ASP.NET)

Do you think that your second sample "2. ASP Alliance Article" will work in an asynchronous web service?
9/26/2007 9:43 AM | Roxane
Gravatar

# re: Redirect to Login page on session expiration (ASP.NET)

gdfggdfgdg
11/22/2007 9:32 PM | fdgdfg
Gravatar

# re: Redirect to Login page on session expiration (ASP.NET)

csccsdcdcdcdscscdcdsdcscssscs
11/22/2007 9:42 PM | fdgdfg
Gravatar

# re: Redirect to Login page on session expiration (ASP.NET)

wwwwwwwwwwwwwwwwwwwwwwwwwww
11/29/2007 2:38 PM | ali
Gravatar

# re: Redirect to Login page on session expiration (ASP.NET)

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...
1/5/2008 12:06 AM | ibrahim
Gravatar

# re: Redirect to Login page on session expiration (ASP.NET)

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?????????
4/8/2008 6:08 PM | Pradeep bisht
Gravatar

# re: Redirect to Login page on session expiration (ASP.NET)

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
4/14/2008 1:22 AM | vinay k
Gravatar

# re: Redirect to Login page on session expiration (ASP.NET)

useless comment for ip image
5/11/2008 4:24 PM | useless comment for ip image
Gravatar

# re: Redirect to Login page on session expiration (ASP.NET)

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);
6/5/2008 5:07 AM | rlively
Gravatar

# re: Redirect to Login page on session expiration (ASP.NET)

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.
6/5/2008 5:22 AM | rlively
Gravatar

#  Redirect to Login page on session expiration (ASP.NET)

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


6/5/2008 6:29 PM | Ved Prakash
Gravatar

# re: Redirect to Login page on session expiration (ASP.NET)

thanx but line 11 error
6/7/2008 9:12 AM | porno video
Gravatar

# re: Redirect to Login page on session expiration (ASP.NET)

Excellent
8/12/2008 10:04 PM | Mohammad javed Comm-IT India Pvt

Post Comment

Title  
Name  
Email
Url
Comment   
Please add 1 and 4 and type the answer here:

Powered by: