Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Update Asp.Net Core Role Claim

How i can change role claim and apply it in terms of one request in Asp.Net Core? I tried to use

_signInManager.RefreshSignInAsync(user);

But it only works after refreshing the page. Is there any way to update roles for user and change current principal in one request?

like image 600
usrere Avatar asked Nov 04 '25 04:11

usrere


1 Answers

You could not change the Current ClaimsPrincipal directly.

To reflect the new claims, you could try _signInManager.CreateUserPrincipalAsync.

To check the new roles in the same request, you may try User.AddIdentity to explict add the new role claim to User.

                var roleName = Guid.NewGuid().ToString();                
            var r1 = User.IsInRole(roleName);

            var user = await _userManager.GetUserAsync(User);
            var role = await _roleManager.CreateAsync(new IdentityRole { Name = roleName });
            await _userManager.AddToRoleAsync(user, roleName);

            var claimsPrincipal = await _signInManager.CreateUserPrincipalAsync(user);
            var claims = claimsPrincipal.Claims.ToList();

            User.AddIdentity(new ClaimsIdentity(new List<Claim>() { claims.FirstOrDefault(c => c.Value == roleName) }));

            var r3 = User.IsInRole(roleName);
like image 74
Edward Avatar answered Nov 06 '25 18:11

Edward



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!