FormsAuthentication.Decrypt 会处理过期值吗?

Will FormsAuthentication.Decrypt work on an expired value?

根据 this SO question 的示例,我的印象是如果您对已过期的 cookie 调用 FormsAuthentication.Decrypt(authCookie.Value),解密仍然有效,我将能够获得值 ticket.UserData(假设它存在于 cookie 中),但值 ticket.Expired 将为真。

我想确认事实确实如此。如果不是,当您解密和过期 cookie 时会发生什么?我已经尝试自己测试过这个,我已经阅读了文档,但我很感激 C# 专家的确认,因为我是 C# 的新手。

谢谢。

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.

因此,如果您收到一个 cookie,那是因为它当时没有过期,FormsAuthentication.Decrypt(authCookie.Value) 会起作用。

下面是一些代码,显示到期日期不会更改您从 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);

最后,如果您收到 cookie,它没有过期,因此应该可以解密