0

Based on the example from this SO question, I was under the impression that if you call FormsAuthentication.Decrypt(authCookie.Value) on a cookie that was expired, the decryption would still work, I would be able to obtain the value ticket.UserData (assuming it exists in the cookie), but the value ticket.Expired would be true.

I would like to confirm that this is in fact the case. If not, what happens when you decrypt and expired cookie? I have tried testing this myself, I have read the docs, but I'd appreciate confirmation from a C# expert just to sure, as I'm new to C#.

Thanks.

Community
  • 1
  • 1
Jonah
  • 15,806
  • 22
  • 87
  • 161

1 Answers1

1

An expired cookie is not sent to the server by the client

You might also want to specify the cookie's expiration date and time. Cookies are normally written to the user's disk, where they could potentially hang around forever. You can therefore specify a date and time on which the cookie expires. When the user visits your site again, the browser first examines the collection of cookies for your site. If a cookie has expired, the browser does not send that particular cookie to the server with the page request; instead, the expired cookie is deleted.

So if you receive a cookie, it's that it was not expired at the time and FormsAuthentication.Decrypt(authCookie.Value) would work.

Here is some code that shows that the expiration date does not change the ticket data you recover from the cookie:

var creationDate = DateTime.Now;
var expirationDate = creationDate.AddSeconds(5);

var ticket = new FormsAuthenticationTicket(1, "ticket", creationDate,
    expirationDate, false, "userData");

var cookie = new Cookie("cookie",
    FormsAuthentication.Encrypt(ticket));
cookie.Expires = expirationDate;

Console.WriteLine("Cookie value: {0}", cookie.Value);
Console.WriteLine("Ticket has expired? {0}", ticket.Expired.ToString());
Console.WriteLine("Ticket userData: {0}", ticket.UserData);

System.Threading.Thread.Sleep(6000);
Console.WriteLine("Cookie and ticket should have expired");

Console.WriteLine("Cookie value: {0}", cookie.Value);

var decryptedTicket = FormsAuthentication.Decrypt(cookie.Value);
Console.WriteLine("Ticket has expired? {0}", decryptedTicket.Expired.ToString());
Console.WriteLine("Ticket userData: {0}", decryptedTicket.UserData);

In closing, if you receive the cookie, it's not expired, and so it should be decryptable

samy
  • 14,832
  • 2
  • 54
  • 82