Specifying ASP.NET Forms Authentication Timeout in Code
Microsoft’s Forms Authentication is the preferred mechanism to get login and security up-and-running on ASP.NET applications. In fact, it comes enabled by default in ASP.NET MVC projects.
Typically, you’d configure the timeout via IIS, or by directly editing the web.config
for the application.
<!-- Example Web Config -->
<authentication mode="Forms">
<forms name=".ASPXAUTH" loginUrl="Login.aspx" protection="All" timeout="1" path="/" slidingExpiration="true" />
</authentication>
By default, your MVC application calls FormsAuthentication.SetAuthCookie()
, which sets a cookie using the timeout declared in your web.config
file. This is good for setting a default timeout, but there may be certain cases where you’d like a longer timeout per user role or some other criteria.
In these cases, you can use a FormsAuthenticationTicket
object to specify your own expiration date, as shown below.
var ticket = new FormsAuthenticationTicket(
version: 1,
name: userName,
issueDate: DateTime.Now,
expiration: DateTime.Now.AddMonths(1),
isPersistent: false,
userData: "");
var encryptedTicket = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
Response.Cookies.Set(cookie);
In this example, I’m instantiating a new FormsAuthenticationTicket
object and setting the expiration date of the cookie to one month from now instead of the one minute from now, as dictated by the timeout="1"
attribute in the web.config
example above.
Next, I use FormsAuthentication.Encrypt()
to encrypt my ticket
. Finally, I create a new cookie using the FormsAuthentication.FormsCookieName
key, using my encryptedTicket
as my cookie value, which I set on the Response.Cookies
collection.
There’s plenty of use cases for functionality like this. In our case, my team needed a way to allow a user to login using a hidden login that would allow them access to only certain parts of the system with an extended timeout.