FormsAuthentication and Session Timeouts

Because the FormsAuthentication and the Session cookies are not the same, it is possible that when you are accessing your application you are still logged in, but the session has expired. In this situation, perhaps the best thing to do is logout from FormsAuthentication and redirect to the same page. You can do this through a custom module. Let's see how:

public class CheckSessionModule: IHttpModule

{

    public void Init(HttpApplication app)

    {

        ctx.Application.AcquireRequestState += this.OnAcquireRequestState;

    }

    public void Dispose() {}

    public void OnAcquireRequestState(Object sender, EventArgs args)

    {

        if ((HttpContext.Current.User.Identity.IsAuthenticated == true) && (HttpContext.Current.Session.IsNewSession == true))

        {

            FormsAuthentication.SignOut();

            HttpContext.Current.Response.Redirect(HttpContext.Current.Request.Url.ToString(), false);

            HttpContext.Current.ApplicationInstance.CompleteRequest();

        }

    }

}

                             

2 Comments

  • We do not log users out when the session expires. Instead we load a default session state. This, in some cases, results in them getting redirected to a default entry page (like the first page they see after they log in).

    Raj

  • Hi, Raj!

    Yes, that is definitely another option, the problem is that the user does not see anything; for example, in a shopping store, if the session expires, and he continues to browse the shop with a default session state, when he checks out, he will find that all the articles in the shopping cart are gone! My approach, at least, lets the user know that something happened.

    Thanks for your post,

    Ricardo

Comments have been disabled for this content.