简体   繁体   English

如何将自定义角色添加到ASP.NET Core

[英]How to add custom roles to ASP.NET Core

I've found this answer but it doesn't seem to fit in my ASP Net Core project. 我找到了这个答案,但它似乎不适合我的ASP Net Core项目。

Things I am trying to understand: 我想要了解的事情:

  • How can I add a custom role. 如何添加自定义角色。 I've even looked directly in my MySQL database (table aspnetroles ), but I don't know what to use as Id and ConcurrencyStamp . 我甚至直接查看我的MySQL数据库(表aspnetroles ),但我不知道如何使用IdConcurrencyStamp
  • Where do I put the code to seed the database with these new roles: in Startup ? 我在哪里放置代码以使用这些新角色为数据库设定种子:在Startup in Register under AccountController ? AccountControllerRegister
  • How do I tie this new role to a user? 如何将此新角色绑定到用户? I've even looked through the tables and I don't know how to assign the data (there is no user2role or aspnetusers.role_id ). 我甚至看过表格,我不知道如何分配数据(没有user2roleaspnetusers.role_id )。

You could do this easily by creating a CreateRoles method in your startup class. 您可以通过在启动类中创建CreateRoles方法来轻松完成此操作。 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<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 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); 然后你可以调用await CreateRoles(serviceProvider); method from the Configure method in the Startup class. Startup类中Configure方法的方法。 ensure you have IServiceProvider as a parameter in the Configure class. 确保将IServiceProvider作为Configure类中的参数。

Edit: If you're using ASP.NET core 2.x, my article here provides a much detailed experience. 编辑:如果您使用的是ASP.NET核心2.x,我的文章提供了非常详细的体验。 here 这里

Adding to Temi's answer and Xavier's comment to it , my experience with this was a little different using . 除了Temi的回答Xavier对它的评论之外 ,我使用经验也有所不同。

In order to get this working I had to add the IServiceProvider as a parameter of the Configure method to get an instance of it. 为了使这个工作,我不得不添加IServiceProvider作为Configure方法的参数来获取它的实例。

public void Configure(
    IApplicationBuilder App,
    IHostingEnvironment Env,
    ILoggerFactory LoggerFactory,
    IServiceProvider ServiceProvider
)
{
    /* trimmed */

    CreateRoles(ServiceProvider).Wait();
}

In addition to Temi's detailed answer, remember to replace 除了Temi的详细答案,请记得更换

 services.AddDefaultIdentity<IdentityUser>()
            .AddEntityFrameworkStores<DbContext>();

With

 services.AddIdentity<IdentityUser, IdentityRole>().AddEntityFrameworkStores<DbContext>();

Also, make sure that the types specified in AddIdentity<> is the same as the types called in serviceProvider.GetRequiredService<> 此外,请确保AddIdentity<>指定的类型与serviceProvider.GetRequiredService<>调用的类型相同

For the above, our types called in serviceProvider.GetRequiredService<> in Configure.cs would be 对于上面的内容,我们在Configure.cs中调用serviceProvider.GetRequiredService<>类型将是

 var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
 var userManager = serviceProvider.GetRequiredService<UserManager<IdentityUser>>();

Another important thing to note is that since CreateRoles(IServiceProvider) (from Temi's answer) is an async method, to call it in Configure method (which return void), you can use CreateRoles(serviceProviderInstance).Wait(); 另一个需要注意的重要事项是,由于CreateRoles(IServiceProvider) (来自Temi的答案)是一个异步方法,要在Configure方法中调用它(返回void),可以使用CreateRoles(serviceProviderInstance).Wait(); Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM