【发布时间】:2021-01-19 02:24:00
【问题描述】:
在从默认 AspNetRole 多对多关系切换到每个用户一个角色并创建自定义身份角色后,User.IsInRole("Admin") 始终返回 false。
登录的用户在数据库上下文中播种,而我删除并再次播种用户以匹配每个用户的一个角色。
这是应用用户:
public class ApplicationUser : IdentityUser
{
// person props
public string RoleId { get; set; }
public ApplicationIdentityRole Role { get; set; }
}
还有身份:
public class ApplicationIdentityRole : IdentityRole<string>
{
public List<ApplicationUser> ApplicationUser { get; set; }
}
这是我的 DBContext:
public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationIdentityRole, string>
{
// DBSets..
protected override void OnModelCreating(ModelBuilder builder)
{
string ADMIN_ID = _config.GetValue<string>("Tokens:SysUsers:Admin");
string ADMIN_ROLE_ID = _config.GetValue<string>("Tokens:Roles:Admin");
builder.Entity<ApplicationIdentityRole>().HasData(new ApplicationIdentityRole
{
Id = ADMIN_ROLE_ID,
Name = "Admin",
NormalizedName = "ADMIN"
});
var hasher = new PasswordHasher<ApplicationUser>();
builder.Entity<ApplicationUser>().HasData(new ApplicationUser
{
Id = ADMIN_ID,
UserName = "admin",
NormalizedUserName = "ADMIN",
Email = "admin@sys.com",
NormalizedEmail = "ADMIN@SYS.COM",
EmailConfirmed = true,
PasswordHash = hasher.HashPassword(null, "123123"),
SecurityStamp = string.Empty,
Title = "Admin",
RoleId = ADMIN_ROLE_ID
});
}
}
并且我已更改启动以匹配应用身份角色类:
services.AddIdentity<ApplicationUser, ApplicationIdentityRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders()
.AddDefaultUI();
services.AddTransient<UserManager<ApplicationUser>>();
登录:
// sigin manager
private readonly SignInManager<ApplicationUser> _signInManager;
// usage
var result = await _signInManager.PasswordSignInAsync(model.UserName, model.Password, model.RememberMe, lockoutOnFailure: false);
授权工作正常,但角色总是返回 false。
我意识到从IdentityDbContext<ApplicationUser, ApplicationIdentityRole, string> 继承会生成默认角色表(多对多),所以理论上,它会将添加给用户的角色属性视为一个数据集AspNetRole 并验证多对多表不是RoleId。
我找不到任何说明如何使用 ef 为每个用户设置一个角色的文档。
非常感谢任何帮助!
更新:成功登录后,SignInManager 不会将角色添加到声明中,而是仅在AspNetUserRole(多对多)表中有记录时添加我想排除。
【问题讨论】:
标签: asp.net-core entity-framework-core asp.net-identity