Wednesday, 19 August 2009

FormsAuthentication Timeout based on different users

I recently was given a requirement to have different FormsAuthentication timeout for different users. I was unsure if this was possible but gave a shot at it.

Generally we specify the timeout in the authentication tag in the web.config:






The timeout specified here applies to all the users using the application. But, we need to override this timeout in our code and set different timeout for different users. ASP.NET allows us to override the timeout via a forms authentication ticket.

The code below illustrates the above feature.

short flag = 0;// or 1 get this flag from db depending on the user
int expirationTime;
if (flag == 0)
{
expirationTime = 10 //u should get these values from web.config;
}
else
{
expirationTime = 20;
}
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(username, false, expirationTime);
string encTicket = FormsAuthentication.Encrypt(ticket);
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket)); Response.Redirect(FormsAuthentication.GetRedirectUrl(username, false));

you create a ticket with the associated username and encrypt it. We then add a cookie to the response. be careful about how sliding expiration works.

Taken from microsoft document: (http://support.microsoft.com/kb/910443)
"Let us take an example: If the logon page is accessed at 5:00 00:00:00 PM, it should expire at 5:10 00:00:00 PM if the timeout attribute is 10 and the slidingExpiration attribute is set to TRUE. Now, if any Web page is browsed again at 5:05 00:00:00 PM, the cookies and ticket time-out period will be reset to 5:15 00:00:00 PM."

So, make sure your cookies work the way you want after setting the sliding expiration to true.