繁体   English   中英

如何在我的 asp.net core 3.1 应用程序中播种用户和角色?

[英]How can I seed users and roles in my asp.net core 3.1 application?

我尝试在我的 IdentityDataContext 类中使用protected override void OnModelCreating(ModelBuilder builder)并创建一个将播种此数据的迁移:

    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);
        // Customize the ASP.NET Identity model and override the defaults if needed.
        // For example, you can rename the ASP.NET Identity table names and more.
        // Add your customizations after calling base.OnModelCreating(builder);
        const string ADMIN_ID = "b4280b6a-0613-4cbd-a9e6-f1701e926e73";
        const string ROLE_ID = ADMIN_ID;
        builder.Entity<IdentityRole>().HasData(new IdentityRole
        {
            Id = ROLE_ID,
            Name = "admin",
            NormalizedName = "ADMIN"
        });
        builder.Entity<MyIdentityUser>().HasData(new MyIdentityUser
        {
            Id = ADMIN_ID,
            UserName = "myemail@myemail.com",
            NormalizedUserName = "MYEMAIL@MYEMAIL.COM",
            Email = "myemail@myemail.com",
            NormalizedEmail = "MYEMAIL@MYEMAIL.COM",
            EmailConfirmed = true,
            PasswordHash = "AQABBAEABCcQAABAEBhd37krE/TyMklt3SIf2Q3ITj/dunHYr7O5Z9UB0R1+dpDbcrHWuTBr8Uh5WR+JrQ==",
            SecurityStamp = "VVPCRDAS3MJWQD5CSW2GWPRADBXEZINA",
            ConcurrencyStamp = "c8554266-b401-4519-9aeb-a9283053fc58"
        });
        builder.Entity<IdentityUserRole<string>>().HasData(new IdentityUserRole<string>
        {
            RoleId = ROLE_ID,
            UserId = ADMIN_ID
        });
    }

这似乎有效,但我无法在用授权属性装饰的 Razor 页面中访问我的端点。 这很奇怪,因为我的数据库中有所有这些数据。 我可以作为这个用户登录,我看到 AspNetRoles 表中有“管理员”角色。 我还在 AspNetUserRoles 表中将用户正确映射到角色。

[Authorize(Roles="admin")]
public class IndexModel : PageModel
{
    public async Task<IActionResult> OnGetAsync()
    {
        return Page();
    }

}

当我以上面的用户身份登录时,我被重定向到访问被拒绝的页面,根据数据库具有管理员角色。

我看到有些人尝试在 Startup 类的 Configure 方法中执行此种子方法,但是当我尝试使用 RoleManager 和 UserManager 执行此操作时,我目前遇到了依赖项注入问题:

System.InvalidOperationException: No service for type 'Microsoft.AspNetCore.Identity.RoleManager`1[Microsoft.AspNetCore.Identity.IdentityRole]' has been registered.

我快到了。 起初并不明显,但我需要在 IdentityHostingStartup.cs 文件的 Configure 方法中添加.AddRoles<IdentityRole>()行。

在 asp.net core 3.1 文档中基于角色的授权页面的末尾提到了这一点: 链接到文档

public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(
            Configuration.GetConnectionString("DefaultConnection")));
    services.AddDefaultIdentity<IdentityUser>()
        .AddRoles<IdentityRole>()
        .AddEntityFrameworkStores<ApplicationDbContext>();

    services.AddControllersWithViews();
    services.AddRazorPages();
}

我认为角色已经被考虑在内,我不需要明确添加这个功能。

应该在页面顶部说明,为了添加基于角色的授权,您需要将.AddRoles<IdentityRole>()到您的 Configure 方法。 相反,您会看到授权属性的许多组合,然后在底部有一个简短的段落“将角色服务添加到身份”,它没有解释这就是使其全部工作的原因。

暂无
暂无

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

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