gpt4 book ai didi

asp.net-mvc - asp.net mvc身份验证cookie问题

转载 作者:行者123 更新时间:2023-12-02 08:57:14 25 4
gpt4 key购买 nike

我正在尝试使用 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 获取用户名的功能。我有两个问题:

  1. 我需要做什么才能检索 Cookie?
  2. 如何解密 cookie 以获得用户名?

最佳答案

获取cookie:

HttpCookie cookie = HttpContext.Current.Request.Cookies.Get(FormsAuthentication.FormsCookieName);

解密它:

FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);
var userName = ticket.UserData

关于asp.net-mvc - asp.net mvc身份验证cookie问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4029369/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com