Jax
Jax

Reputation: 997

Reading from authentication cookie

I'm trying to read the username from an auth ticket (which is TESTTEST)

-----LOGIN PAGE------

FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1,
      "TESTTEST",
      DateTime.Now,
      DateTime.Now.AddMinutes(30),
      false,
      String.Empty,
      FormsAuthentication.FormsCookiePath);
            string encryptedTicket = FormsAuthentication.Encrypt(ticket);
            HttpCookie authCookie = new HttpCookie(
                            FormsAuthentication.FormsCookieName,
                            encryptedTicket);
            authCookie.Secure = true;
            Response.Cookies.Add(authCookie);
             FormsAuthentication.RedirectFromLoginPage("User", false);

------Protected page -------

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

Results : label text is "USER" instead of "TESTTEST"

What can I do to fix this and get the correct value?

Upvotes: 1

Views: 2164

Answers (1)

Dmitry Osinovskiy
Dmitry Osinovskiy

Reputation: 10118

FormsAuthentication.RedirectFromLoginPage creates a new ticket with supplied name ("User" in your case). From http://msdn.microsoft.com/en-us/library/ka5ffkce.aspx

If the CookiesSupported property is true, and either the ReturnUrl variable is within the current application or the EnableCrossAppRedirects property is true, then the RedirectFromLoginPage method issues an authentication ticket and places it in the default cookie using the SetAuthCookie method.

You may want to use the following code instead of RedirectFromLoginPage

returnUrl = FormsAuthentication.GetRedirectUrl(userName, false);
HttpContext.Current.Response.Redirect(returnUrl);

Upvotes: 1

Related Questions