Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UserData property of FormsAuthenticationTicket is empty despite being set

For some reason, I the UserData property of my authentication cookie is empty. Here is the code:

var authCookie = FormsAuthentication.GetAuthCookie(userName, rememberUser.Checked);
// Get the FormsAuthenticationTicket out of the encrypted cookie
var ticket = FormsAuthentication.Decrypt(authCookie.Value);
// Create a new FormsAuthenticationTicket that includes our custom User Data
var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration, ticket.IsPersistent, "userData");
// Update the authCookie's Value to use the encrypted version of newTicket
authCookie.Value = FormsAuthentication.Encrypt(newTicket);
// Manually add the authCookie to the Cookies collection
Response.Cookies.Add(authCookie);
FormsAuthentication.RedirectFromLoginPage(userName, rememberUser.Checked);

Here is how I try to access it:

if (HttpContext.Current.Request.IsAuthenticated )
{
    var authCookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName];
    if (authCookie != null)
    {
        var authTicket = FormsAuthentication.Decrypt(authCookie.Value);
        string data = authTicket.UserData;
        // data is empty !!!
    }
}
like image 1000
laconicdev Avatar asked May 16 '13 18:05

laconicdev


2 Answers

RedictFromLoginPage overwrites your cookie. Remove this line and redirect manually (Response.Redirect).

like image 78
Wiktor Zychla Avatar answered Nov 17 '22 10:11

Wiktor Zychla


This is a similar answer I answered few days ago.

https://stackoverflow.com/a/16365000/296861

You cannot use FormsAuthentication.SetAuthCookie or FormsAuthentication.RedirectFromLoginPage if you create FormsAuthenticationTicket by yourself.

like image 20
Win Avatar answered Nov 17 '22 08:11

Win