Update FormsAuthenticationTicket

In a recent project the role of the user was decided at a later point after login, based on some dropdown selection. But the FormsAuthenticationTicket was created at login as below

 FormsAuthenticationTicket ticket = new FormsAuthenticationTicket(1, // Ticket version  
       userName, // Username associated with ticket
      
DateTime.Now, //Date/time issued

      
DateTime.Now.AddMinutes(20), // Date/time to expire

      
false, // "true"for a persistent user cookie

    
userRole, // User-data, in this case the roles

    
FormsAuthentication.FormsCookiePath);

string
hash = FormsAuthentication.Encrypt(ticket);
HttpCookie
cookie = new HttpCookie(FormsAuthentication.FormsCookieName,// Name of auth cookie
hash); //Hashed ticket

// Set the cookie's expiration time to the tickets expiration time
if
(ticket.IsPersistent) cookie.Expires = ticket.Expiration;

// Add the cookie to the list for outgoing response

HttpContext.Current.Response.Cookies.Add(cookie);

So to update the roles in the FormAuthenticationTicket we need to first read the ticket from cookie and create new one from that and then add role values as below

// Read the cookie
HttpCookie cookie = FormsAuthentication.GetAuthCookie(Session[Constants.UserName].ToString(), true);

// Decrypt the cookie to get ticket

FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(cookie.Value);

// Create new ticket from old and update roles
FormsAuthenticationTicket newticket = new FormsAuthenticationTicket                     (ticket.Version, // Ticket version
ticket.Name, // Username associated with ticket

       
ticket.IssueDate, // Date/time issued
ticket.Expiration, // Date/time to expire                     false, //"true" for a persistent user cookie                     DropDownListRole.SelectedItem.Text, //User-data, in this case the roles from a dropdown                     ticket.CookiePath);

// Encrypt the ticket and store it in the cookie
cookie.Value = FormsAuthentication.Encrypt(newticket);

// Set the cookie's expiration time to the tickets expiration time
if (ticket.IsPersistent) cookie.Expires = newticket.Expiration;

// Add the cookie to the list for outgoing response

HttpContext.Current.Response.Cookies.Add(cookie);





Similar Articles