更新 ASP.NET One Core 中的声明值

Update Claims values in ASP.NET One Core

我在 MVC 6(Asp.Net One Core)中有一个 Web 应用程序,并且我正在使用基于声明的身份验证。在登录方法中,我设置了声明:

var claims = new Claim[]
{
    new Claim("Name", content.Name),
    new Claim("Email", content.Email),
    new Claim("RoleId", content.RoleId.ToString()),
};

var ci = new ClaimsIdentity(claims, "password");
await HttpContext.Authentication.SignInAsync("Cookies", new ClaimsPrincipal(ci));

现在,如果用户更改了用户个人资料中的电子邮件,我该如何更改 "Email" 声明的电子邮件值?我必须再次 SignOutAsync 和 SignInAsync 才能更新 cookie?最好的解决方案是将其保存到经典会话中?有更好的解决办法吗?我完全错了?

有什么建议吗?

I have to SignOutAsync and SignInAsync again in order to update the cookie?

答案是肯定的。

最简单的方法是您可以在更新电子邮件的同一操作方法中手动注销和登录(再次创建声明)

The best solution is to save this into a classic session?

我建议不要那样做。在 ASP.Net MVC 中显式使用会话状态是一种不好的做法。

另一个选项,而不是 SignOutAsyncSignInAsync,是使用 RefreshSignInAsync

示例:

var user = await _userManager.FindByIdAsync(yourId);
await _signInManager.RefreshSignInAsync(user);

查看SignInManager(net 5.0.8)中的RefreshSignInAsync代码: https://github.com/dotnet/aspnetcore/blob/ae2eabad0e49302d0632a7dde917fdc68d960dc4/src/Identity/Core/src/SignInManager.cs#L170