Updating a user role with identity in .net core without relogging

Viewed 57

I'm updating the role of a user with the following code :

string UserID = User.FindFirstValue(ClaimTypes.NameIdentifier);
                var user = await _userManager.FindByIdAsync(UserID);
                
                var roles = await _userManager.GetRolesAsync(user);

                if (User.IsInRole(Roles.niveau1.ToString()))
                {
                    List<string> lstRolesASupprimer = new() { Roles.niveau1.ToString() };
                    List<string> lstRolesAAjouter = new() { Roles.niveau2.ToString() };
                    var result = await _userManager.RemoveFromRolesAsync(user, lstRolesASupprimer);
                    result = await _userManager.AddToRolesAsync(user, lstRolesAAjouter);
                }

The problem is that the user must disconnect and reconnect to activate the new role. Is it possible to change the user role immediatly ?

Thanks

1 Answers

The identity information(roles,claims) are put into the cookie when the user logs in. Since the user is already logged in, this line of code _userManager.AddToRolesAsync(user, lstRolesAAjouter) will update the db , but not the cookie. You have to have to re-issue the cookie.

Try add

SignInManager.SignIn(user, false, false); 

after

result = await _userManager.AddToRolesAsync(user, lstRolesAAjouter);
Related