4

Is it possible to have a cookie expire at the end of a session, or at a specific time?

Rush Frisby
  • 11,388
  • 19
  • 63
  • 83
  • 2
    Session cookies expire at the end of a session. – Oded Oct 03 '11 at 19:41
  • If the session expires on the server, then the browser's cookie contains a now-bogus value. Thus, it shouldn't really hurt anything if it remains unexpired on the browser. Of course, I suppose there might be aesthetic reasons for expiring the cookie on the browser... – mikemanne Oct 03 '11 at 19:42
  • if the user leaves their browser open forever, i want it to expire after a few hours in that case. – Rush Frisby Oct 03 '11 at 19:42
  • It's pretty much like the session cookies *are* the session. They're the link between your web server datastore and your enduser. When one of them becomes unavailable (e.g. due to the cookie expiration) the session ends. The GC on your server side will eventually destroy the session, but there's no user who can access it anymore (I'm pretty sure asp.net got session hijacking prevention built in). – cutsoy Oct 03 '11 at 19:45
  • session ending = as in the browser closes. not the asp.net session. – Rush Frisby Oct 03 '11 at 19:56

3 Answers3

1

Yep! It's simple

HttpCookie newCookie = new HttpCookie("myCookie");
newCookie.Expires = DateTime.Today.AddDays(1);

If you want the cookie to be for the session, set it to DateTime.MinValue. See the MSDN Documentation here for more info. Here's the excerpt:

Setting the Expires property to MinValue makes this a session Cookie, which is its default value.

Bengel
  • 1,043
  • 7
  • 12
1

since this is not possible with a single cookie i am sending two cookies. the auth cookie expires at the end of the session. the second cookie expires at a specific time. on each request i check the second cookie and if it is null i log the user out manually.

Rush Frisby
  • 11,388
  • 19
  • 63
  • 83
0

You can control cookie life time with Expires and Max-Age properties. Anyway if session is expired or you invalidate it impliclty, cookie associated with this session (for example jsessionId) are not valid anymore.

user12384512
  • 3,362
  • 10
  • 61
  • 97