Paritosh
Paritosh

Reputation: 4503

UseCookieAuthentication and SessionTimeout

We are currently building an MVC 4 application which uses Cookie Authentication, using Owin, we have this in out Startup class.

        public void ConfigureAuth(IAppBuilder app)
    {
        // Enable the application to use a cookie to store information for the signed in user
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,
            LoginPath = new PathString("/Account/Login"),
            ExpireTimeSpan = TimeSpan.FromMinutes(30)   // users requested timeout be increased to 30 mins
        });

        //***************************** Specific to our App **************************************************
        //This is requrired to tell AntiForgeryConfig to use NameIdentifier as a unique key to validate against 
        AntiForgeryConfig.UniqueClaimTypeIdentifier = ClaimTypes.NameIdentifier;

    }

Another developer working on this project wants to store a value in Session, but we noticed when debugging that the Session timeout is set to 20 mins. Can we sync them, so they are the same value? Or are we not supposed to mix the two?

Upvotes: 2

Views: 2238

Answers (1)

MichaelCleverly
MichaelCleverly

Reputation: 2543

Your Session timeout is handled in the Web.config, whereas the Owin cookie timeout is handled by the library, as you referred to in your example.

Your session timeout is set in the web.config like this:

<system.web>
   <sessionState timeout="60"  />
</system.web>

As far as I know, there is no way of syncing these 2 timeouts.

A way of solving this, could be to set you sessionState to a lower number than your Owin ExpireTimeSpan, and make a Custom ActionAttribute to use on your controllers, that checks if the session has timed out - and then you can do what you want. It can be a very easily implemented solution, and could look something like this:

public class RedirectingActionAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var session = HttpContext.Current.Session["SessionVar"];

        //Redirects user to login screen if session has timed out
        if (session == null)
        {
            base.OnActionExecuting(filterContext);


            filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
            {
                controller = "Home",
                action = "Index"
            }));
        }

    } 
}

The method above, is invoked whenever a controller with the follow ActionAttribute is called in the scope:

[RedirectingAction]
public class HomeController : Controller
{
//Controller code
}

Upvotes: 1

Related Questions