如何在asp.net core 3.1应用程序中为用户和角色设定种子?

问题描述 投票:0回答:1

我尝试在我的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 = "[email protected]",
            NormalizedUserName = "[email protected]",
            Email = "[email protected]",
            NormalizedEmail = "[email protected]",
            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
        });
    }

这似乎有效,但是我无法访问装饰有Authorize atribute的Razor Page中的端点。这很奇怪,因为我的数据库中有所有这些数据。我可以以该用户身份登录,并且看到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.

c# asp.net-core authorization roles asp.net-core-3.1
1个回答
0
投票
© www.soinside.com 2019 - 2024. All rights reserved.