【发布时间】:2019-08-04 23:59:27
【问题描述】:
我正在尝试使用 ASP.NET MVC 实现“记住我”功能。它使用如下定义的自定义身份验证过程。
Web.config:
<authentication mode="Forms">
<forms loginUrl="/Account/Login" defaultUrl="/Home/MyAccount" timeout="43200"/>
</authentication>
保存 cookie 的代码:
public void SignIn(string userName, bool createPersistentCookie) {
int timeout = createPersistentCookie ? 525600 : 120; // Timeout in minutes, 525600 = 365 days.
FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(userName, createPersistentCookie, timeout);
string encrypted = FormsAuthentication.Encrypt(ticket);
HttpCookie cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encrypted);
cookie.Expires = System.DateTime.Now.AddMinutes(timeout);
HttpContext.Current.Response.Cookies.Add(cookie);
FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
}
获取 cookie 的代码:
if (System.Web.HttpContext.Current.Request.Cookies.AllKeys.Contains(FormsAuthentication.FormsCookieName)) {
cookie = System.Web.HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
}
当前代码检查 Session 以进行身份验证。我还想添加从 cookie 获取用户名的功能。我有两个问题:
- 我需要做什么才能检索 cookie?
- 如何解密cookie获取用户名?
【问题讨论】:
标签: asp.net-mvc