How to decrypt FormsAuthenticationTicket in mvc c#?

6.4k views Asked by At

I am encrypt the password and store it to session value using FormsAuthenticationTicket, when I retrieve it I can not able to decrypt the password.

Encrypt like below

    string pw="xyz";
    FormsAuthenticationTicket ticketpw = new FormsAuthenticationTicket(pw, true, 1000);
    string securepw = FormsAuthentication.Encrypt(ticketpw);

    Session["password"] = securepw;

I tried to Decrypt Like below
Try 1

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

            Session["password"] = securepw;

Try 2

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

Error - Can not convert FormAuthenticationTicket to String

1

There are 1 answers

4
Ahmed On BEST ANSWER

Because you create new ticket differently than ticket it got encrypted. Best practice is to put it in an HttpCookie and then retrieve it:

  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));

And decrypt:

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