Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create roles in ASP.NET Core and assign them to users?

I am using the ASP.NET Core default website template and have the authentication selected as "Individual User Accounts". How can I create roles and assign it to users so that I can use the roles in a controller to filter access?

like image 638
Bipn Paul Avatar asked Feb 26 '17 17:02

Bipn Paul


People also ask

Can we assign roles to users?

Assign roles in user profileYou can also assign roles to users from their individual profile page. Go to Dashboard > User Management > Users and click the name of the user. Click the Roles view, and click Assign Role. Choose the role you wish to assign and click Assign.


2 Answers

My comment was deleted because I provided a link to a similar question I answered here. Ergo, I'll answer it more descriptively this time. Here goes.

You could do this easily by creating a CreateRoles method in your startup class. This helps check if the roles are created, and creates the roles if they aren't; on application startup. Like so.

private async Task CreateRoles(IServiceProvider serviceProvider)     {         //initializing custom roles          var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();         var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();         string[] roleNames = { "Admin", "Manager", "Member" };         IdentityResult roleResult;          foreach (var roleName in roleNames)         {             var roleExist = await RoleManager.RoleExistsAsync(roleName);             if (!roleExist)             {                 //create the roles and seed them to the database: Question 1                 roleResult = await RoleManager.CreateAsync(new IdentityRole(roleName));             }         }          //Here you could create a super user who will maintain the web app         var poweruser = new ApplicationUser         {              UserName = Configuration["AppSettings:UserName"],             Email = Configuration["AppSettings:UserEmail"],         };     //Ensure you have these values in your appsettings.json file         string userPWD = Configuration["AppSettings:UserPassword"];         var _user = await UserManager.FindByEmailAsync(Configuration["AppSettings:AdminUserEmail"]);         if(_user == null)        {             var createPowerUser = await UserManager.CreateAsync(poweruser, userPWD);             if (createPowerUser.Succeeded)             {                 //here we tie the new user to the role                 await UserManager.AddToRoleAsync(poweruser, "Admin");              }        }     } 

and then you could call the CreateRoles(serviceProvider).Wait(); method from the Configure method in the Startup class. ensure you have IServiceProvider as a parameter in the Configure class.

Using role-based authorization in a controller to filter user access: Question 2

You can do this easily, like so.

[Authorize(Roles="Manager")] public class ManageController : Controller {    //.... } 

You can also use role-based authorization in the action method like so. Assign multiple roles, if you will

[Authorize(Roles="Admin, Manager")] public IActionResult Index() { /*  .....  */  } 

While this works fine, for a much better practice, you might want to read about using policy based role checks. You can find it on the ASP.NET core documentation here, or this article I wrote about it here

like image 179
Temi Lajumoke Avatar answered Sep 20 '22 21:09

Temi Lajumoke


I have created an action in the Accounts controller that calls a function to create the roles and assign the Admin role to the default user. (You should probably remove the default user in production):

    private async Task CreateRolesandUsers()     {           bool x = await _roleManager.RoleExistsAsync("Admin");         if (!x)         {             // first we create Admin rool                 var role = new IdentityRole();             role.Name = "Admin";             await _roleManager.CreateAsync(role);              //Here we create a Admin super user who will maintain the website                                 var user = new ApplicationUser();             user.UserName = "default";             user.Email = "[email protected]";              string userPWD = "somepassword";              IdentityResult chkUser = await _userManager.CreateAsync(user, userPWD);              //Add default User to Role Admin                 if (chkUser.Succeeded)             {                 var result1 = await _userManager.AddToRoleAsync(user, "Admin");             }         }          // creating Creating Manager role              x = await _roleManager.RoleExistsAsync("Manager");         if (!x)         {             var role = new IdentityRole();             role.Name = "Manager";             await _roleManager.CreateAsync(role);         }          // creating Creating Employee role              x = await _roleManager.RoleExistsAsync("Employee");         if (!x)         {             var role = new IdentityRole();             role.Name = "Employee";             await _roleManager.CreateAsync(role);         }   } 

After you could create a controller to manage roles for the users.

like image 32
Stephane Duteriez Avatar answered Sep 16 '22 21:09

Stephane Duteriez