Search
Close this search box.

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 |

This article is part of the GWB Archives. Original Author:  Shahed Khan (MVP)

Related Posts