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;
authCookie.Secure = true;
Using this is simple, just add the attribute to your required action like so:
public ActionResult SomeAction()