【问题标题】:OWIN/Identity FrameworkOWIN/身份框架
【发布时间】:2015-03-24 13:41:04
【问题描述】:

我有一个带有 SignIn 方法的类库,其中包含很多逻辑,以便成员登录。我面临的问题是我在身份中添加了“全名”声明,它工作正常,但是一旦用户注销并再次登录,声明就消失了。

如果我检查用户身份,则该声明在第二次登录时可用,直到 RedirectToAction 方法被命中,那么所有自定义声明都不再存在于用户身份中。这包括 Fullname 和 Role 声明。


var roles = _dbsme.sp_GetAllRoles(user.Id);
ClaimsIdentity identity = await _userManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
AuthenticationProperties authenticationProperties1 = new AuthenticationProperties();
authenticationProperties1.IsPersistent = false;
AuthenticationProperties authenticationProperties2 = authenticationProperties1;
identity.AddClaim(new Claim("FullName", user.Firstname + " " + user.Surname));
foreach (string role in roles)
{
    identity.AddClaim(new Claim(ClaimTypes.Role, role));
}

AuthenticationManager.SignIn(authenticationProperties2, identity);
signInStatus = SignInStatus.Success;

【问题讨论】:

  • 您是否在下次请求时检查身份?即不是设置身份并将其登录的当前请求?
  • @Shoe,你将如何在下一个请求中检查身份?我觉得奇怪的是,第一次登录时效果很好,但是如果用户注销然后再次登录,那么 RedirectToAction 上的声明就会被删除(在帐户控制器中)。我不从类库重定向。
  • User.Identity 获取用户的当前身份。重定向后,您可以检查声明对象。

标签: c# asp.net-identity owin


【解决方案1】:

您应该通过UserManager 添加声明以使它们持久化(如果您将 ASP.NET Identity 2 与 EF 一起使用)。

userManager.AddClaim(userId, new Claim(claimType,claimValue));

请注意,如果您为当前登录的用户添加声明,您需要再次登录该用户(将新信息放入 cookie)。

【讨论】:

  • 我改变了我的“identity.AddClaim(new Claim(ClaimTypes.Role, role));”到“_userManager.AddClaim(user.Id, new Claim(ClaimTypes.Role, role));”并且该过程现在正在100%运行。谢谢@pysco68。经过更深入的研究,我发现了这个身份。AddClaim 使用 mscorlib,而 usermanager 使用 Microsoft.AspNet.Identity.Core 和 claimstore。简而言之....不要在 ASP.Net Identity 2 中直接使用身份。
  • @Inox 您可以“直接”使用声明。事实上,如果您查看 UserManager 中引用的类,您会发现它们指向 mscorlib
  • @Shoe,我也是这样做的,但是由于某些未知原因,索赔在索赔商店中没有正确设置。但是用户管理器添加声明方法显然确实正确。当我直接使用它时,在与同一用户的同一会话中登录、关闭和再次登录时会出现奇怪的行为。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-05
  • 1970-01-01
  • 2013-07-30
  • 2015-10-09
  • 2015-09-23
  • 1970-01-01
相关资源
最近更新 更多