I have a two blocks of codes which are supposed to do the same job, that is copying the whole FormsAuthenticationTicket
and changing one bit of it which is stored in UserData
.
The first code reads correctly everything including UserData
. The second does not include UserData
. It simply returns an empty string. I realised that when an exception was thrown because if an empty object.
Any idea?
The first code:
string cookieName = FormsAuthentication.FormsCookieName;
HttpCookie authCookie = HttpContext.Request.Cookies[cookieName];
if (authCookie != null)
{
FormsAuthenticationTicket oldTicket = FormsAuthentication.Decrypt(authCookie.Value);
UserData userDataObj = JsonConvert.DeserializeObject<UserData>(oldTicket.UserData);
userDataObj.PassChangeRequired = user.PasswordChangeRequired;
string userdata = JsonConvert.SerializeObject(userDataObj);
FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(
oldTicket.Version,
oldTicket.Name,
oldTicket.IssueDate,
oldTicket.Expiration,
oldTicket.IsPersistent,
userdata,
oldTicket.CookiePath);
authCookie.Value = FormsAuthentication.Encrypt(newTicket);
Response.Cookies.Set(authCookie);
}
The second code:
HttpCookie authCookie = FormsAuthentication.GetAuthCookie(user.UserName, false);
if (authCookie != null)
{
FormsAuthenticationTicket oldTicket = FormsAuthentication.Decrypt(authCookie.Value);
UserData userDataObj = JsonConvert.DeserializeObject<UserData>(oldTicket.UserData);
userDataObj.PassChangeRequired = user.PasswordChangeRequired;
string userdata = JsonConvert.SerializeObject(userDataObj);
FormsAuthenticationTicket newTicket = new FormsAuthenticationTicket(
oldTicket.Version,
oldTicket.Name,
oldTicket.IssueDate,
oldTicket.Expiration,
oldTicket.IsPersistent,
userdata,
oldTicket.CookiePath);
authCookie.Value = FormsAuthentication.Encrypt(newTicket);
Response.Cookies.Set(authCookie);
}
If you look at the MSDN for the GetAuthCookie() method that you use in example 2, you will see that it says:
Creates an authentication cookie for a given user name.
What this means is that when you make this call in example 2, you are actually getting back a brand new authentication cookie that was just created and not the one that you have already set. This is why the UserData
property is empty/null.