Remove all Roles from a user MVC 5
Asked Answered
A

2

13

Peace be upon you

I am trying to remove all roles from a user to disable his permissions and prevent him from accessing some pages.

I found this method to remove one role and it worked:

await UserManager.RemoveFromRoleAsync(userid, role);

Where userid is the user ID that I want to disable his permission.

So, I use this code to delete all roles from the same user

foreach (string role in roles) {

 await UserManager.RemoveFromRoleAsync(userid, role);

}

But I stuck here how to save roles Id which are in AspNetRoles table to

string[] roles 

Any help?

or is there another way to delete all roles from a user?

I am using asp.net identity version 2

Angelenaangeleno answered 10/12, 2016 at 10:40 Comment(0)
V
37

User manager has a method Task<IList<string>> GetRolesAsync(TKey userId) which

Returns the roles for the user

And also Task<IdentityResult> RemoveFromRolesAsync(TKey userId, params string[] roles) that

Remove user from multiple roles

so combine the two to achieve what you want

var roles = await UserManager.GetRolesAsync(userid);
await UserManager.RemoveFromRolesAsync(userid, roles.ToArray());
Village answered 10/12, 2016 at 13:1 Comment(7)
Thanks for your fast replying.. When I used the two lines that wrote, an error occurred the error message: cannot convert from Ilist<string> to string, I solved this problem by using await UserManager.RemoveFromRolesAsync(userid, roles.ToString()); But roles did not removedAngelenaangeleno
My mistake. convert the roles to a string array. The original call returns a list but the second method needs an array. I had forgotten to convert it to an array. I have updated answer to reflect changes.Village
WORKED.. Thanks a lot!Angelenaangeleno
Does UserManager.Delete remove roles automatically?Jayejaylene
Apparently you have to first fetch the roles and then convert them to an array. Solely calling RemoveFromRolesAsync(user, new string[] { "Administrator" } doesn't work! Because the roles were not fetched in the context of .NET Core's Identity implementation? I can't hardly believe but got no result with directly calling the remove method.Fritzie
@BernoulliIT This code is from asp.net mvc 5+ not Core. There may have been changes since then.Village
Check. In .NET Core it doesn't work in a single call which is odd. Anyway thanks for your tip ;)Fritzie
L
0

I am new to all this, but I tried to update and delete roles from a Blazor page. This code seemed to work.

Set up using and injections:

@using Microsoft.AspNetCore.Identity
@using Microsoft.Extensions.Configuration

@inject RoleManager<IdentityRole> roleManager
@inject UserManager<IdentityUser> userManager
@inject SignInManager<IdentityUser> signInManager
@inject AuthenticationStateProvider userData

Page element code:

<h3>Access Roles</h3>

<select class="custom-select custom-select-sm" @onchange="SetUserAccess">
    <option value="-1" disabled selected>Select access...</option>

    @foreach (var access in typeAccess)
    {
        <option value="@access">@access</option>
    }

</select>

<p>
    <h5>@message</h5>
</p>

C# code:

@code
{
    private UserRoles _userRoles = new UserRoles();
    private List<string> typeAccess = new List<string>();
    private IList<string> oldRoles = new List<string>();
    private string newRole = "";
    private string message = "";



    protected override void OnParametersSet()
    {
        base.OnParametersSet();
        typeAccess.Add("Administrator");
        typeAccess.Add("Employee");
        typeAccess.Add("Office Staff");
    }

    private async Task SetUserAccess(ChangeEventArgs selectedAccess)
    {
        foreach (var role in typeAccess)
        {
            var roleExist = await roleManager.RoleExistsAsync(role);

            if (roleExist == false)
            {
                await roleManager.CreateAsync(new IdentityRole(role));
            }
        }

        var authState = await userData.GetAuthenticationStateAsync();
        string userName = authState.User.Identity.Name;
        var user = await userManager.FindByEmailAsync(userName);
        

        if (user != null)
        {
            oldRoles = await userManager.GetRolesAsync(user);
            newRole = selectedAccess.Value.ToString();

            @for (int i = 0; i < oldRoles.Count; i++)
            {
                await userManager.RemoveFromRolesAsync(user, oldRoles);
            }

            await userManager.AddToRoleAsync(user, newRole);
        }

        message = $"{ userName } has had their role changed from { oldRoles[0] } to { newRole }.";
    }
}

This deleted all roles existing and set the new role.

Larina answered 11/10, 2020 at 18:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.