Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 731
O. Haifa Avatar asked Dec 10 '16 10:12

O. Haifa


1 Answers

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());
like image 149
Nkosi Avatar answered Nov 12 '22 21:11

Nkosi