【问题标题】:Changing HttpContext.Current.User.Identity.Name更改 HttpContext.Current.User.Identity.Name
【发布时间】:2018-03-07 08:50:13
【问题描述】:

在 SetAuthCookie 部分,我们稍微像这样操作用户名

string userInfo = identity.Name + "|"  + Util.GetIPAddress();
FormsAuthentication.SetAuthCookie(userInfo, isPersistent);

这是为了检查Application_AuthenticateRequest中的用户IP地址

稍后我想将名称恢复为正常名称(没有“|”和 IP 地址)但找不到方法。

我遇到的问题通常处理用户名没有正确更新,但我需要重新分配名称。

我尝试设置一个新的 cookie 并设置一个新的 Authcookie 但它们不起作用,HttpContext.Current.User.Identity.Name 没有改变。

我该怎么做?

【问题讨论】:

  • 对我来说似乎是一个 XY 问题 (meta.stackexchange.com/questions/66377/what-is-the-xy-problem) - 与其更改您的用户名,不如告诉我们您在 Application_AuthenticateRequest 中要做什么,这需要用户 IP 地址
  • 说实话,这也是我的担忧之一。基本上,我们正在尝试将 IP 添加到 cookie,以便我们可以检测 IP 更改并在同一用户从不同 IP 登录时删除会话。我只是按照我的吩咐去做。

标签: c# asp.net-mvc httpcontext roleprovider


【解决方案1】:

构建您自己的身份验证 cookie 以添加您需要的自定义值是一种更好的方法,这样您就可以保持用户名不变,从而更加一致和预期的行为。

考虑到这样做,您在 cookie 中加密了用户数据(IP)。

    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);

另外,您可以从当前的 User.Identity 中检索此 userData

var data = (HttpContext.Current?.User.Identity as FormsIdentity)?.Ticket.UserData

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-06
    相关资源
    最近更新 更多