有没有办法将附加信息添加到 ASP.NET 身份验证 cookie 中?我想将我自己的内部用户密钥保存在 cookie 中,并让它与每个问题的 auth cookie 同时过期: MVC save a token in session
问问题
686 次
1 回答
2
[Serializable]
public class CookieDto
{
public string Username { get; set; }
public string UserId { get; set; }
public string AuthenticationKey { get; set; }
public bool Persist { get; set; }
public string RememberMeToken { get; set; }
}
坚持方法,
public void Persist(CookieDto cookieDto, bool persistent)
{
var serializer = new XmlSerializer();
var serializedCookie = serializer.Serialize(cookieDto);
var ticket = new FormsAuthenticationTicket(1, cookieDto.Username, DateTime.Now, DateTime.Now.AddDays(90),
persistent, serializedCookie);
var encryptedTicket = FormsAuthentication.Encrypt(ticket);
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket) { Expires = DateTime.Now.AddDays(90) };
HttpContext.Current.Response.Cookies.Add(cookie);
}
获取方法,
public CookieDto GetCookie()
{
var cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
if (cookie != null && !string.IsNullOrEmpty(cookie.Value))
{
var ticket = FormsAuthentication.Decrypt(cookie.Value);
var serializer = new XmlSerializer();
return serializer.Deserialize<CookieDto>(ticket.UserData);
}
return null;
}
删除方法,
public void RemoveCookie()
{
FormsAuthentication.SignOut();
}
祝你好运!
于 2013-05-14T07:18:11.137 回答