O. Haifa
O. Haifa

Reputation: 145

Remove all Roles from a user MVC 5

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

Upvotes: 13

Views: 17021

Answers (2)

Andrew Hillas
Andrew Hillas

Reputation: 1

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.

Upvotes: 0

Nkosi
Nkosi

Reputation: 247088

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());

Upvotes: 37

Related Questions