关于 c#: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# 新手。

谢谢。


客户端未将过期的cookie发送到服务器

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 中恢复的票证数据:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
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,它还没有过期,所以它应该是可解密的