Monday, April 6, 2009

Manual Sliding Expiration

When using ASP.NET Forms Authentication, ASP.NET sets a timeout of 30 minutes by default for which a user is logged in. If the user does make a request within the 30 minutes, the authentication ticket is renewed for a another period. This normally happens behind the scenes and the developer is often not aware of this process, known as sliding expiration.

However, if you've got some pages on your web application that should be viewable by the user without the authentication ticket being renewed (such as a ticker to display new messages within an IFrame), you can disable slidingExpiration by making the following change in the web.config file:

<authentication mode="Forms">
<forms slidingExpiration="false"></forms>

You then have to programatically perform sliding expiration within your code, which can be done with the following code snippet posted at:

// Acquire Auth Ticket from the FormsIdentity object
FormsAuthenticationTicket objOrigTicket = ((FormsIdentity)Context.User.Identity).Ticket;

if (!Request.Url.AbsolutePath.ToLower().EndsWith(".ashx"))
// Manually slide the expiration
FormsAuthenticationTicket objNewTicket = FormsAuthentication.RenewTicketIfOld(objOrigTicket);

if (objNewTicket.Expiration > objOrigTicket.Expiration)
// Create the (encrypted) cookie.
HttpCookie objCookie = new HttpCookie(FormsAuthentication.FormsCookieName, FormsAuthentication.Encrypt(objNewTicket));
// Add the cookie to the list for outbound response.
// Update original
objOrigTicket = objNewTicket;

In the code snippet above, you would have to change the condition within the IF statement that checks Request.Url to exclude the pages for which you do not want slidingExpiration to occur. The example above excludes all requests to ASP.NET Generic Handlers (files ending in .ashx).

No comments:

Post a Comment