36

We know that form authentication cookie is encrypted. so how to read the form authentication cookie content from my code behind.

if (Request.Cookies[".ASPXAUTH"] != null)
{
    HttpCookie myCookie = new HttpCookie(".ASPXAUTH");
}
Rubens Mariuzzo
  • 28,358
  • 27
  • 121
  • 148
Thomas
  • 33,544
  • 126
  • 357
  • 626
  • Possible duplicate http://stackoverflow.com/questions/2921387/get-the-aspxauth-cookie-value-programatically – xsari3x Aug 28 '11 at 10:16

1 Answers1

87

You can access the ticket with the Decrypt method provided by FormsAuthentication

HttpCookie authCookie = Request.Cookies[FormsAuthentication.FormsCookieName];
FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(authCookie.Value);

string cookiePath = ticket.CookiePath;
DateTime expiration = ticket.Expiration;
bool expired = ticket.Expired;
bool isPersistent = ticket.IsPersistent;
DateTime issueDate = ticket.IssueDate;
string name = ticket.Name;
string userData = ticket.UserData;
int version = ticket.Version;
Zach S.
  • 130
  • 1
  • 9
RyanW
  • 5,338
  • 4
  • 46
  • 58
  • How to extract data from ticket....suppose i create auth cookie like below one way. FormsAuthenticationTicket ticket = new FormsAuthenticationTicket( 1, username, DateTime.Now, DateTime.Now.AddMinutes(30), isPersistent, userData, FormsAuthentication.FormsCookiePath); so how get the above data from ticket after decrypt ? plzz guide me.......thanks – Thomas Aug 28 '11 at 18:17
  • After decrypt, you can access properties directly on the ticket. This shows the list of properties: http://msdn.microsoft.com/en-us/library/system.web.security.formsauthenticationticket.aspx . I updated the answer with an example of accessing the data in the ticket. – RyanW Aug 29 '11 at 14:26
  • just a typo: ticket.IsPersistant should be ticket.IsPersistent – Raghav May 20 '12 at 11:29
  • 3
    Thanks for this. Also, I believe on last line, version should be int, not string. But I am using ASP.NET 4.5.... – Jason Parker Oct 24 '12 at 19:14
  • This is brilliant – Himalaya Garg Apr 08 '21 at 08:21