asp.net-mvccookiesforms-authenticationsetcookieformsauthentication

Is it possible to update FormsAuthentication cookie value?


I have to set FormsAuthentication cookie value (FormsAuthentication.SetAuthCookie(UserDesignation, false)) at the time of login. Now I need to provide designation change option. So when user change their designation, I need to update the FormsAuthentication cookie value from old designation to new designation.

Is it possible to do that?

If yes means, how can I do this?


Solution

  • You can modify the cookie data as shown below, but it is preferable as per me to keep the role in a separate cookie and authenticate it using the FormsAuthentication cookie

    HttpCookie cookie = FormsAuthentication.GetAuthCookie(Username, true);
    var ticket = FormsAuthentication.Decrypt(cookie.Value);
    
    var newticket = new FormsAuthenticationTicket(ticket.Version,
                                                  ticket.Name,
                                                  ticket.IssueDate,
                                                  ticket.Expiration,
                                                  true, //persistent 
                                                  "user data,designation",
                                                  ticket.CookiePath);
    
    cookie.Value = FormsAuthentication.Encrypt(newticket);
    cookie.Expires = newticket.Expiration.AddHours(2);
    HttpContext.Current.Response.Cookies.Set(cookie);