Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update Claims values in ASP.NET One Core

I have a Web Application in MVC 6 (Asp.Net One Core), and I'm using Claims based authentication. In the Login method I set the Claims:

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));

Now, if the user for example changes the email in the user profile, how can I change the e-mail value for the "Email" Claim? I have to SignOutAsync and SignInAsync again in order to update the cookie? The best solution is to save this into a classic session? There is a better solution? I'm totally wrong?

Any suggestions?

like image 347
Martín Avatar asked Aug 18 '16 20:08

Martín


2 Answers

Another option, instead of SignOutAsync and SignInAsync, is to use RefreshSignInAsync.

Example:

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

View the RefreshSignInAsync code in the SignInManager (net 5.0.8): https://github.com/dotnet/aspnetcore/blob/ae2eabad0e49302d0632a7dde917fdc68d960dc4/src/Identity/Core/src/SignInManager.cs#L170

like image 157
Alex Avatar answered Sep 19 '22 23:09

Alex


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

Answer is yes.

Easiest way is you can manually sign-out and sign-in (create claims again) inside the same action method where you are updating the email.

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

I suggest not to do that. Using session state explicitly is a bad practice in ASP.Net MVC.

like image 37
Win Avatar answered Sep 20 '22 23:09

Win