1
有沒有辦法將其他信息添加到ASP.NET身份驗證cookie中?我想保存在cookie中我自己的內部用戶密鑰,並使其失效,同時按照這一問題的權威性的cookie: MVC save a token in session將附加信息添加到ASP.net auth cookie?
有沒有辦法將其他信息添加到ASP.NET身份驗證cookie中?我想保存在cookie中我自己的內部用戶密鑰,並使其失效,同時按照這一問題的權威性的cookie: MVC save a token in session將附加信息添加到ASP.net auth cookie?
[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;
}
remove方法,
public void RemoveCookie()
{
FormsAuthentication.SignOut();
}
祝你好運!
謝謝,不錯的片段。 –