MVC session expiring but not authentication

Josh Russo picture Josh Russo · Sep 5, 2012 · Viewed 9.5k times · Source

I'm developing a C# MVC application and I can't seem to get the Authentication and Session timeouts to synchronize. I have a basic Forms Authentication setup and some limited session values. I set the Authentication timeout less than the session (28 minutes vs 30) but running against the development web server, the session will be wiped on a restart of the server but the authentication sticks around. I'm assuming that the authentication is being stored in a cookie that obviously survives the server restart.

<authentication mode="Forms" >
  <forms loginUrl="~/Account/Login" timeout="28" />
</authentication>
<sessionState timeout="30" />

I think I want to force the the authentication to timeout if Session is null, to then force a login.

Is that what I actually want to do? If so how and where do I do this?

If not, what is the proper way to handle this?

EDIT

For more of a perspective I also posted this question for this same project: Login as... best practices?

Answer

Josh Russo picture Josh Russo · Nov 12, 2012

I found my answer. Override the Authorize attribute. This seems like the most elegant approach:

public class AuthorizeWithSessionAttribute : AuthorizeAttribute
{
    protected override bool AuthorizeCore(HttpContextBase httpContext)
    {
        if (httpContext.Session == null || httpContext.Session["CurrentUser"] == null)
            return false;

        return base.AuthorizeCore(httpContext);
    }

}