OWIN/Identity 框架

OWIN/Identity Framework

我有一个 class 库,它的 SignIn 方法包含很多逻辑,以便成员登录。我面临的问题是我添加了 "Fullname" 的声明到身份并且它工作正常,但是一旦用户注销并再次登录,声明就消失了。

如果我检查用户身份,声明在第二次登录时可用,直到命中 RedirectToAction 方法,然后所有自定义声明都不再在用户身份中。这包括全名和角色声明。


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;

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

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

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