如何在 asp.net 核心 3.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 = "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();
}
}

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

我看到有些人尝试在启动类的配置方法中执行此种子方法,但是当我尝试使用角色管理器和用户管理器执行此操作时,我目前在依赖项注入方面遇到问题:

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

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

核心3.1 文档中基于角色 asp.net 授权页面末尾提到了它: 文档链接

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>()添加到配置方法中。相反,您会看到授权属性的许多组合,然后在底部有一个简短的段落"将角色服务添加到身份",其中没有解释这是使这一切起作用的原因。

最新更新