How to add custom roles to ASP.NET Core

前端 未结 3 1654
暗喜
暗喜 2021-02-04 11:11

I\'ve found this answer but it doesn\'t seem to fit in my ASP Net Core project.

Things I am trying to understand:

  • How can I add a custom role. I\'ve even l
3条回答
  •  -上瘾入骨i
    2021-02-04 11:22

    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)
        {
            //adding customs roles : Question 1
            var RoleManager = serviceProvider.GetRequiredService>();
            var UserManager = serviceProvider.GetRequiredService>();
            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 2
                    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"],
            };
    
            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 : Question 3
                    await UserManager.AddToRoleAsync(poweruser, "Admin");
    
                }
           }
        }
    

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

    Edit: If you're using ASP.NET core 2.x, my article here provides a much detailed experience. here

提交回复
热议问题