Question

How do I make cookies expire after a set time period? For example, in five minutes time for security reasons.

Answer

Depending on how you use the data stored in a cookie, it is often a good idea to make the cookie expire. Since anyone using the browser will have the cookie sent on their behalf, it may appear to be a legitimate user when in actual fact it is not. This often happens in places like Internet cafes, school or university computing labs, or libraries. If your cookie sends a user identifier that facilitates access to sensitive data, or allows changes to be made (for example, a web-based email service), then you should expire cookies after a small time period. If the user keeps using your servlet, you always have the option of resending the cookie with a longer duration.

To specify an expiration time, you can use the setMaxTime(int) method of javax.servlet.http.Cookie. It takes as a parameter the number of seconds before the cookie will expire. For example, for a five minute expiration, we would do the following :-

// Create a new cookie for userID from a fictitious
// method called getUserID
Cookie cookie = new Cookie ("userID", getUserID());

// Expire the cookie in five minutes (5 * 60)
cookie.setMaxTime( 300 );

When the cookie is sent back to the browser, using HttpServletResponse.addCookie(Cookie), it will only be returned by the browser until the expiration date occurs. If you'd prefer, you can also specify a negative value for setMaxTime(int), and the cookie will expire as soon as the browser exits. Note however that not everyone will shutdown their browser, and it might be available for minutes, hours even days. Finally, specifying a value of zero will expire the cookie instantly.


Back