如何在ASP.NET Core 2.2中创建角色并将其分配给用户



我正在使用ASP.NET Core 2.2默认网站模板和选择作为单个用户帐户的身份验证。如何创建"管理员"角色并将其分配给用户,以便我可以在控制器中使用角色来过滤访问并让他们看到不同的页面。这是我到目前为止在互联网上找到的,但它行不通,因为它说:ApplicationUser could not be found

private void CreateRoles(IServiceProvider serviceProvider)
        {
            var roleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
            var userManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
            Task<IdentityResult> roleResult;
            string email = "someone@somewhere.com";
            //Check that there is an Administrator role and create if not
            Task<bool> hasAdminRole = roleManager.RoleExistsAsync("Administrator");
            hasAdminRole.Wait();
            if (!hasAdminRole.Result)
            {
                roleResult = roleManager.CreateAsync(new IdentityRole("Administrator"));
                roleResult.Wait();
            }
            //Check if the admin user exists and create it if not
            //Add to the Administrator role
            Task<ApplicationUser> testUser = userManager.FindByEmailAsync(email);
            testUser.Wait();
            if (testUser.Result == null)
            {
                ApplicationUser administrator = new ApplicationUser();
                administrator.Email = email;
                administrator.UserName = email;
                Task<IdentityResult> newUser = userManager.CreateAsync(administrator, "_AStrongP@ssword!");
                newUser.Wait();
                if (newUser.Result.Succeeded)
                {
                    Task<IdentityResult> newUserRole = userManager.AddToRoleAsync(administrator, "Administrator");
                    newUserRole.Wait();
                }
            }
        }

为我的应用程序管理管理员的任何帮助将不胜感激。

第一步是创建可用于扩展索赔的ApplicationUser类:

public class ApplicationUser : IdentityUser
{
}

修改_LoginPartial.cshtml以使用该类:

@inject SignInManager<ApplicationUser> SignInManager
@inject UserManager<ApplicationUser> UserManager

Data文件夹中修改ApplicationDbContext.cs以分配ApplicationUserIdentityRole

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, IdentityRole, string>
{
    public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
        : base(options)
    {
    }
}

修改Startup.cs以使用新的ApplicationUser和角色管理启用:

services.AddDefaultIdentity<ApplicationUser>()
    .AddRoles<IdentityRole>()
    .AddDefaultUI(UIFramework.Bootstrap4)
    .AddEntityFrameworkStores<ApplicationDbContext>();

之后,您可以播种以镀箱角色并分配给用户:

private async Task CreateUserRoles(IServiceProvider serviceProvider)
{
    var RoleManager = serviceProvider.GetRequiredService<RoleManager<IdentityRole>>();
    var UserManager = serviceProvider.GetRequiredService<UserManager<ApplicationUser>>();
    IdentityResult roleResult;
    //Adding Admin Role
    var roleCheck = await RoleManager.RoleExistsAsync("Admin");
    if (!roleCheck)
    {
        //create the roles and seed them to the database
        roleResult = await RoleManager.CreateAsync(new IdentityRole("Admin"));
    }
    //Assign Admin role to the main User here we have given our newly registered 
    //login id for Admin management
    ApplicationUser user = await UserManager.FindByEmailAsync("v-nany@hotmail.com");
    await UserManager.AddToRoleAsync(user, "Admin");
}

使用:

public void Configure(IApplicationBuilder app, IHostingEnvironment env,IServiceProvider serviceProvider)
{
    .......
    app.UseAuthentication();
    app.UseMvc(routes =>
    {
        routes.MapRoute(
            name: "default",
            template: "{controller=Home}/{action=Index}/{id?}");
    });
    CreateUserRoles(serviceProvider).Wait();
}

相关内容

  • 没有找到相关文章

最新更新