我尝试在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
});
}
这似乎可行,但是我无法在装饰有Authorize atribute的Razor Page中访问我的端点。这很奇怪,因为我所有这些数据都存储在数据库中。我可以以该用户身份登录,并且看到AspNetRoles表中有“管理员”角色。我还将用户正确映射到AspNetUserRoles表中的角色。
[Authorize(Roles="admin")]
public class IndexModel : PageModel
{
public async Task<IActionResult> OnGetAsync()
{
return Page();
}
}
以用户身份登录时,我被重定向到“拒绝访问”页面,根据该用户,根据数据库,该用户具有管理员角色。
我看到有人尝试在Startup类的Configure方法中执行此种子方法,但是当我尝试使用RoleManager和UserManager进行依赖注入(inject)时,我目前遇到麻烦:
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文档的“基于角色的授权”页面的末尾提到了这一点:
link to the documentation
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();
}
我认为角色已经被考虑在内,因此不需要显式添加此功能。在页面顶部应该指出,为了添加基于角色的授权,您需要在自己的Configure方法中添加
.AddRoles<IdentityRole>()
。取而代之的是为您提供许多Authorization属性的组合,然后在底部有一个简短的段落“向Identity添加角色服务”,没有给出任何解释说明这是使一切正常运行的原因。