Using web-api 2 and identity 2, I'm trying to create an action to remove a user from roles using user id and role names. I'm using the ApplicationUserManager provided by the nuget identity2 sample.
My action
[HttpPost]
[Route("RemoveUserFromRole")]
public async Task<IHttpActionResult> RemoveUserFromRole(UserRolesViewModel model)
{
if (!ModelState.IsValid)
return BadRequest(ModelState);
var result = await UserManager.RemoveUserFromRolesAsync(
model.UserId, model.RoleNames);
if (result.Errors.Any())
return InternalServerError();
return Ok();
}
My view model:
public class UserRolesViewModel
{
[Required]
public string UserId { get; set; }
[Required]
public IList<string> RoleNames { get; set; }
}
ApplicationUserManager's RemoveUserFromRolesAsync:
public virtual async Task<IdentityResult> RemoveUserFromRolesAsync(
string userId, IList<string> roles)
{
var userRoleStore = (IUserRoleStore<ApplicationUser, string>) Store;
var user = await FindByIdAsync(userId).ConfigureAwait(false);
if (user == null)
throw new InvalidOperationException("Invalid user Id");
var userRoles = await userRoleStore.GetRolesAsync(user).ConfigureAwait(false);
foreach (var role in roles.Where(userRoles.Contains))
await userRoleStore.RemoveFromRoleAsync(user, role).ConfigureAwait(false);
return await UpdateAsync(user).ConfigureAwait(false);
}
My issue is that given a user belonging to the roles 'User' and 'Mod', the user cannot be removed from 'Mod'. Posting the following json removes the user from the role 'User' as expected:
{
"userId": "0d5f97e4-65a0-43ad-b889-0af98a7ff326",
"roleNames": [
"User"
]
}
But given the following json, user is not removed from 'Mod', but is instead removed from 'User':
{
"userId": "0d5f97e4-65a0-43ad-b889-0af98a7ff326",
"roleNames": [
"Mod"
]
}
Debugging shows that when given the role 'Mod', the correct user id and role name are passed into userRoleStore.
This was a bug that should be fixed in version 2.0.1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With