简体   繁体   中英

Changing HttpContext.Current.User.Identity.Name

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM