Reputation: 1199
During SetAuthCookie part we are manipulating user name slightly like this
string userInfo = identity.Name + "|" + Util.GetIPAddress();
FormsAuthentication.SetAuthCookie(userInfo, isPersistent);
this is in order to make some checks with users IP Address inside Application_AuthenticateRequest
Later on I want to revert the name back to its normal (without "|" and IP address) but couldn't find a way to do it.
Questions I came across generally handled the user name not updating correctly but what I need is to reassign the name.
I tried to set a new cookie and set a new Authcookie but they didnt work, HttpContext.Current.User.Identity.Name
doesn't change.
How can I do this?
Upvotes: 0
Views: 2210
Reputation: 2414
It is a better aproach to build your own authentication cookie to add the custom values you need, that way you keep the username unchanged wich is more consistent and the expected behavior.
Take into account doing this, you have the userdata (the ip) encrypted in the cookie.
var cookie = FormsAuthentication.GetAuthCookie(name, rememberMe);
var ticket = FormsAuthentication.Decrypt(cookie.Value);
var newTicket = new FormsAuthenticationTicket(ticket.Version, ticket.Name, ticket.IssueDate, ticket.Expiration,ticket.IsPersistent, userData, ticket.CookiePath);
var encTicket = FormsAuthentication.Encrypt(newTicket);
cookie.Value = encTicket;
//and add the cookie to the current HttpContext.Response
response.Cookies.Add(cookie);
Additionaly, you can retrieve this userData back from the current User.Identity
var data = (HttpContext.Current?.User.Identity as FormsIdentity)?.Ticket.UserData
Upvotes: 1