【发布时间】:2020-04-01 09:17:30
【问题描述】:
我尝试在我的 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.
【问题讨论】:
-
您能分享您的 startup.cs 以便我尝试复制它吗?
标签: c# asp.net-core authorization roles asp.net-core-3.1