Sailr Solutions

App development and consulting

Overriding session cookies in asp.net MVC

Working on an existing web app for a customer recently we come across an interesting requirement.&nb

Working on an existing web app for a customer recently we come across an interesting requirement. 

The site used normal forms based authentication with a session expiry of 25 minutes. However we were building a new controller and associated views and the requirement was that users remained signed in for 10 hours.  

We opted for an approach that uses a custom action filter and thought it worth posting the code in case it's of benefit to someone else. 

 [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
    public class ExtendedAuthTimeOutHours : ActionFilterAttribute
    {
        private readonly int _hours;
        private const int TicketVersion = 1;
        private const bool IsPersistent = true;

        public ExtendedAuthTimeOutHours(int hours)
        {
            _hours = hours;
        }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            HttpContext ctx = HttpContext.Current;
            var user = ctx.User.Identity.Name;

            FormsAuthenticationTicket authTicket = new FormsAuthenticationTicket(TicketVersion, user, DateTime.Now, DateTime.Now.AddHours(_hours), IsPersistent, "");
            string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
            HttpCookie authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
            authCookie.HttpOnly = true;
            if (SSLRedirect.RequireSSL())
            {
                authCookie.Secure = true;
            }
            ctx.Response.Cookies.Add(authCookie);
            base.OnActionExecuting(filterContext);
        }
    }

Using this is simple, just add the attribute to your required action like so:

 [ExtendedAuthTimeOutHours(10)]
        public ActionResult SomeAction()
        {
            return View();
        }