Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC3: C# Forms Authentication and Session State

I would like to know the best way to handle and implement session time outs in MVC. I have setup my app so that it can handle the "RememberMe" when the user authenticate. I also stores some variables in Context.Session["myvar"];

I run into a problem when my session has expired but my authentication cookie has not yet expired.

My first thought was to check the session stat on on action request; but that seems like a lot of code. Is there a good place to check the session state once? What are other ways to handle a session time out? I would like the user to be redirected to the login page when a session has timedout. or have the session variables reloaded if the user is still logged in.

like image 342
Arcadian Avatar asked Dec 10 '22 00:12

Arcadian


1 Answers

Is there a good place to check the session state once

Sure, a custom Authorize attribute looks like a great place:

public class MyAuthorizeAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        var authroized = base.AuthorizeCore(httpContext);
        if (!authroized)
        {
            // the user is not authenticated or the forms authentication
            // cookie has expired
            return false;
        }

        // Now check the session:
        var myvar = httpContext.Session["myvar"];
        if (myvar == null)
        {
            // the session has expired
            return false;
        }

        return true;
    }
}
like image 184
Darin Dimitrov Avatar answered Dec 23 '22 23:12

Darin Dimitrov