Search This Blog

Wednesday, February 5, 2014

Helpful ASP.NET forms authenication and session timeout article


From Adam Tuliper's Development Tips

What happens when user session timeouts before Form authenication does?

http://completedevelopment.blogspot.com/2009/12/caution-with-using-sessiontimeout-and.html

Modifield code from Adam's article:

Add the following code to global.asax to reroute request to login if session has expired:

protected void Application_PreRequestHandlerExecute(object sender, EventArgs e)
        {
            //Only access session state if it is available
            if (Context.Handler is IRequiresSessionState || Context.Handler is IReadOnlySessionState)
            {
                //If we are authenticated AND we dont have a session here.. redirect to login page.
                HttpCookie authenticationCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
                if (authenticationCookie != null)
                {
                    FormsAuthenticationTicket authenticationTicket = FormsAuthentication.Decrypt(authenticationCookie.Value);
                    if (authenticationTicket != null && !authenticationTicket.Expired)
                    {
                        if (Session["username"] == null)
                        {
                            //This means for some reason the session expired before the authentication ticket. Force a login.
                            FormsAuthentication.SignOut();
                            Response.Redirect(FormsAuthentication.LoginUrl, true);
                            return;
                        }
                    }
                }
            }
        }