Is there a way to add additional information into the ASP.NET authentication cookie? I would like to save my own internal user key in the cookie, and have it expire at the same time as the auth cookie per this question: MVC save a token in session
Asked
Active
Viewed 756 times
1 Answers
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; }
}
Persist method,
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);
}
Get method,
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 method,
public void RemoveCookie()
{
FormsAuthentication.SignOut();
}
Good Luck!

Ömer Faruk Aplak
- 889
- 2
- 9
- 21