【问题标题】:asp.net mvc authentication cookie issueasp.net mvc 身份验证 cookie 问题
【发布时间】: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 获取用户名的功能。我有两个问题:

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

【问题讨论】:

    标签: asp.net-mvc


    【解决方案1】:

    获取 cookie:

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

    解密它:

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

    【讨论】:

    • 谢谢,效果很好。我也意识到我需要删除代码 FormsAuthentication.SetAuthCookie(userName, createPersistentCookie);
    猜你喜欢
    • 1970-01-01
    • 2017-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-30
    • 2011-02-28
    • 1970-01-01
    相关资源
    最近更新 更多