dotnet / dotnet/aspnetcore

UserManager.AddToRolesAsync() and RemoveFromRolesAsync() fail on any conflict

Open
#55,772 1 comment 3 reactions 0 assignees View on GitHub
area-identity enhancement
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 10h
Merged PRs (30d)
281

Description

### Is there an existing issue for this?

- [X] I have searched the existing issues

### Describe the bug

When adding multiple roles or generally updating a user's roles, `UserManager.AddToRolesAsync()` will fail upon finding that the user already has one of the given roles. Similary, `UserManager.RemoveFromRolesAsync()` will fail if the user does not have any of the given roles to be removed.

### Expected Behavior

`UserManager.AddToRolesAsync()` should add all given roles to the user and simply skip any that the user already has and `UserManager.RemoveFromRolesAsync()` should remove all given roles from the user and simply skip any that the user does not have.

### Steps To Reproduce

``` CSharp
// with userManager coming from dependency injection and user being the IdentityUser object for some user
string role1 = "Role1";
await userManager.AddToRoleAsync(user, role1); // success
string[] roleGroup = [ "Role1", "Role2", "Role3" ];
IdentityResult result = await userManager.AddToRolesAsync(user, roleGroup);
if (!result.Succeeded) { throw new Exception("Failed to add roles"); } // will always throw here
```

### Exceptions (if any)

_No response_

### .NET Version

8.0.101

### Anything else?

_No response_

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.