Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AspNetCore.Identity RemoveFromRoleAsync does not remove role from user

I'm using ASP.NET Core Identity 2.0.2. When I call UserManager.RemoveFromRoleAsync, it does not remove the role from the user. It says:

Microsoft.AspNetCore.Identity.UserManager: Warning: User b651a459-5d6b-4239-88e6-facb33f11e87 is not in role Administrator.

Here's the code:

var userResult = await _userManager.RemoveFromRoleAsync(
    user,
    requestRole.ToReadableString());

I also tried to pass the role as an array in the RemoveFromRolesAsync function to no avail.

I don't see any other way to remove a role from a user.


Update

var roleResult = await _userManager
    .IsInRoleAsync(
        user,
        requestRole.ToReadableString());

var roleResult2 = await _userManager
    .IsInRoleAsync(
        user,
        "Administrator");

var roles = await _userManager
    .GetRolesAsync(user);

var userResult = await _userManager
    .RemoveFromRoleAsync(
        user,
        requestRole.ToReadableString());

roleResult and roleResult2 are both false.
roles contains "Administrator".
the user has the Role "Administrator" if I login with this user.
So the Authorize Attribute says the user has this role:

[Authorize(Roles = "Administrator", AuthenticationSchemes = "Bearer")]

Antoher test:

var roles = await _userManager
    .GetRolesAsync(user);

foreach (string role in roles)
{
    var roleTempResult = await _userManager
        .IsInRoleAsync(
            user,
            role);
}

The method IsInRoleAsync() returs false for all the roles returned from GetRolesAsync(user);
Whats going on there?

like image 313
Andre Avatar asked Feb 04 '26 14:02

Andre


1 Answers

I hit this exact problem as well.

The problem was that the user I was passing in to all these functions was not a complete IdentityUser. It was an instance of IdentityUser and had the correct Id, UserName and Email, but other values like NormalizedEmail, NormalizedUserName and PasswordHash had been discarded when the user was retrieved in an earlier process.

Once I changed the retrieve process to not transform the users returned from GetUsersInRoleAsync, (I'd been populating a list with new IdentityUser instances based on the returned users and only setting the values I needed. Changing this to populate the list with the actual returned users fixed the problems), IsInRoleAsync and RemoveFromRoleAsync worked as expected.

like image 65
Greg Holden Avatar answered Feb 06 '26 03:02

Greg Holden



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!