ASP.NET Identity用户名获胜';t在注销/登录后刷新

本文关键字:注销 登录 刷新 Identity NET 用户 获胜 ASP | 更新日期: 2023-09-27 18:30:00

我们使用的是ASP.NET Identity 2.0,希望允许更改用户名。当它被更改时,会发生以下情况:

  1. 用户已注销=>无错误
  2. 用户名在数据库中更改=>工作,更改可见
  3. 用户使用新用户名登录=>工作,但仍显示旧用户名

问题是第3步,在登录后,用户仍然使用旧用户名返回,即使在数据库中是新用户名,使用新用户名登录也有效。

我尝试了以下方法来清除现有的引用:

Context.GetOwinContext().Authentication.SignOut(); // also tried it with DefaultAuthenticationTypes.ExternalCookie
Session.Clear();
Session.Abandon();
// sign in with the new username => no problem
IdentityHelper.SignIn(manager, user, false);
// added this later, when the rest didn't work, but didn't help either
Context.User = new System.Security.Principal.GenericPrincipal(new System.Security.Principal.GenericIdentity(user.UserName), roles);
// tried this too, but didn't help either
System.Web.Security.FormsAuthentication.SetAuthCookie(user.UserName, true);
// after executing the following statement, user always has the old username
var user = Context.User.Identity.GetUserName();

所有语句执行时都不会出错。还有什么需要做的吗?

编辑

还尝试通过循环清除缓存

foreach (System.Collections.DictionaryEntry entry in HttpContext.Current.Cache)
    HttpContext.Current.Cache.Remove(entry.Key as string);

以及Context.Application.Clear();

还尝试擦除用户,即"Context.user=null",但这导致登录时出现异常。当我执行"user=manager"时。Find("newUserName",password)'登录时,它会返回用户,但即使是用新用户名检索的,它实际上仍然包含旧用户名。不知道我还应该澄清什么。

ASP.NET Identity用户名获胜';t在注销/登录后刷新

因为我把头发扯掉了,所以也发布了这个答案:)

我尝试了所有的东西,甚至是上面列出的重定向。然而,我偶然发现了这篇文章http://benfoster.io/blog/aspnet-identity-stripped-bare-mvc-part-2注意到他使用的是签出,只是他指定了的类型

_applicationSignInManager.AuthenticationManager.SignOut("ApplicationCookie") 

我没有把它留空,而是尝试了一下,效果很好!没有重定向。

所以我的代码看起来像这样-

_applicationSignInManager.AuthenticationManager.SignOut("ApplicationCookie");
FormsAuthentication.SignOut(); // doing for good measure (might not need)
// Sign back in (Does the password sign in etc)
var resultSignIn = helper.PasswordSignIn(userName: userName, password: password, isPersistent: false, shouldLockout: true);
// Update the HttpContext with the new user
HttpContext.Current.User = new GenericPrincipal(new GenericIdentity(userName), new string[] { });

将此作为答案发布,以防其他人对此感到愤怒。事实证明,重定向确实解决了问题,但它需要在signOut和signIn之间完成。

如果重定向发生在登录之后,就像我以前尝试过的那样,那么旧值将被保留。因此,在重定向过程中,某些内容似乎被清除了,我无法手动删除,但在再次登录之前需要清除。