'Force MVC CookieAuthentication to timeout prematurely, then setup combination of sliding and absolute expiration

I am maintaining a website that using cookie authentication in a ASP.NET MVC5 application. When the application went live the cookie time out is set to a very long time, say 99999 minutes.

In an effort to increase security, I decided that the timeout should be 60 minute at the most. Even with sliding expiration, I should force users to re-login after a day or so. Now I am facing two problems:

  1. How to I force those who already logged in with the forever valid cookie (99999 minutes) to re-authenticate themselves?

  2. Can I set a sliding expiration for 60 minutes, combined with a absolute expiration in 1 day? (Thus disallowing them to refresh the web indefinitely so that it never expires)

The following is the original time-out setting:

    public void ConfigureAuth(IAppBuilder app)
    {
        // other code
        app.UseCookieAuthentication(new CookieAuthenticationOptions
        {
            AuthenticationType = DefaultAuthenticationTypes.ApplicationCookie,              
            LoginPath = new PathString("/Login"),
            ExpireTimeSpan = TimeSpan.FromMinutes(99999),
        });
    }


Solution 1:[1]

After setting a time for the session to die in login:

    public void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var httpContext = filterContext.HttpContext;
        var isAuthenticated = httpContext.User.Identity.IsAuthenticated;
        //if not authenticated, let something else handle that
        if (!isAuthenticated)
            return;
        var sessionEndTimeObject = httpContext.Session[SessionLimit.TimeOutString];
        
        if (sessionEndTimeObject != null)
        {
            var sessionRequiredEndTime = (DateTime) sessionEndTimeObject;
            var now = DateTime.Now;
            //if their session is supposed to end, kick
            if(sessionRequiredEndTime <= now)
            {
                Kick(filterContext);
            }
        }
        else //the value isn't set, kick
        {
            Kick(filterContext);
        }
    }
    private void Kick(ActionExecutingContext filterContext)
    {
        var authentication = filterContext.HttpContext.GetOwinContext().Authentication;
        authentication.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
        filterContext.HttpContext.Session.Clear();
        filterContext.HttpContext.Session.Abandon();
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 mcfea