You need to call _signInManager.Context.SignInAsync
with updated ClaimsIdentity
.
Here is a working demo:
1.Extension for signin with new ClaimsIdentity
:
public class CustomClaimsCookieSignInHelper<TIdentityUser> where TIdentityUser : IdentityUser
{
private readonly SignInManager<TIdentityUser> _signInManager;
public CustomClaimsCookieSignInHelper(SignInManager<TIdentityUser> signInManager)
{
_signInManager = signInManager;
}
public async Task SignInUserAsync(ClaimsIdentity claimsIdentity)
{
await _signInManager.Context.SignInAsync(IdentityConstants.ApplicationScheme, new ClaimsPrincipal(claimsIdentity));
}
}
2.Register CustomClaimsCookieSignInHelper<TIdentityUser>
:
services.AddTransient<CustomClaimsCookieSignInHelper<IdentityUser>>();
3.Update User Claims:
public class IndexModel : PageModel
{
private readonly CustomClaimsCookieSignInHelper<IdentityUser> _signInHelper;
public IndexModel(CustomClaimsCookieSignInHelper<IdentityUser> signInHelper)
{
_signInHelper = signInHelper;
}
public async Task<IActionResult> OnGetAsync()
{
var claims = new List<Claim>()
{
new Claim("token","value")
};
var identity = HttpContext.User.Identities.FirstOrDefault();
identity.AddClaims(claims);
await _signInHelper.SignInUserAsync(identity);
return Page();
}
}
BTW,if you use jwt authentication
,When server side get the API call with token , the AddJwtBearer
will decode token ,validate token and make user authenticated, you can add new claims either in OnTokenValidated
or in custom middleware. But the claims won't persist in next api calls.So if you want to get updated claim in another request, a new token must be issued.