修改后使ClaimsPrincipal无效

时间:2019-02-13 05:56:08

标签: asp.net-mvc asp.net-mvc-4 claims-based-identity asp.net-identity-2

我正在使用ASP.NET MVC Identity2。

我添加了“名字”自定义ClaimPrincipal

public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser, long> manager)
{
    var userIdentity = await manager.CreateIdentityAsync(
                           this,
                           DefaultAuthenticationTypes.ApplicationCookie);

    // Add custom user claims here
    userIdentity.AddClaim(new Claim("FirstName", FirstName));

    return userIdentity;
}

如果更新“ FirstName”的值,则需要注销并重新登录,以更新“ FirstName”声明。是否有可能使“名字”声明无效,因此其值被强制刷新?


我看过this question,它显示了如何更新Claims的值,我想知道是否有更简单的方法来使它们无效。

1 个答案:

答案 0 :(得分:1)

在查看MS内置模板时,我注意到他们总是在更改用户凭据(例如密码,2因子身份验证等)后呼叫SignInManager.SignInAsync

我还注意到,一旦用户注销并重新登录,Claims就会更新。因此,在更改存储在Claim中的“ FirstName”之后,我叫{{1} }重新登录用户...这样,SignInManager.SignInAsync就会更新:

Claims

注意:如问题所示,我将[HttpPost] [ValidateAntiForgeryToken] public async Task<ActionResult> UpdateFirstName(string firstName) { var user = await UserManager.FindByIdAsync(User.Identity.GetUserId<long>()); user.FirstName = firstName; // update FirstName which is stored in a Claim var result = await UserManager.UpdateAsync(user); if (result.Succeeded) { // re-signin the user, to refresh the Claims await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); // you need to redirect after calling SignInAsync, so claims are refreshed return RedirectToAction("Index"); } // add some error message... return View(); } 存储在Cookie中。