如何在mvc c#中解密FormsAuthenticationTicket?

时间:2016-12-23 09:29:54

标签: c# asp.net-mvc-4 form-authentication

我使用 FormsAuthenticationTicket 加密密码并将其存储到会话值,当我检索密码时,我无法解密密码。

加密如下

            FormsAuthenticationTicket ticketuname = new FormsAuthenticationTicket(pw, true, 1000);
            string secureuname = FormsAuthentication.Decrypt(pw);

            Session["password"] = securepw;

我试图解密如下
尝试1

            string securepw=FormsAuthentication.Decrypt(pw);               
            Session["password"] = securepw;

尝试2

{{1}}

错误 - 无法将FormAuthenticationTicket转换为字符串

1 个答案:

答案 0 :(得分:3)

因为您创建了新的票证难以对票证进行加密,所以最佳做法是将其放入HttpCookie然后检索它

  FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
    username,
    DateTime.Now,
    DateTime.Now.AddMinutes(30),
    isPersistent,
    userData,
    FormsAuthentication.FormsCookiePath);

  // Encrypt the ticket.
  string encTicket = FormsAuthentication.Encrypt(ticket);

  // Create the cookie.
  Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));

并且堕落

var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];

if (authCookie == null) return;
var cookieValue = authCookie.Value;

if (String.IsNullOrWhiteSpace(cookieValue)) return;
var ticket = FormsAuthentication.Decrypt(cookieValue)

https://msdn.microsoft.com/en-us/library/system.web.security.formsauthentication.encrypt(v=vs.110).aspx