Search code examples
c#asp.netasp.net-mvcasp.net-coreasp.net-identity-3

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?


Solution

  • 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 = "default@default.com";
    
                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.