【发布时间】:2019-02-27 13:44:55
【问题描述】:
我们在项目中使用基于用户角色的授权。我们需要在我们的表(用户角色表)中添加一个属性,这会导致用户在该属性建立时拥有角色。例如,我们想说位置 X 中的用户 A 具有特殊角色,但位置 Y 中的同一用户具有其他角色。 (使用 .net 核心)
【问题讨论】:
标签: c# asp.net-core-mvc asp.net-core-identity
我们在项目中使用基于用户角色的授权。我们需要在我们的表(用户角色表)中添加一个属性,这会导致用户在该属性建立时拥有角色。例如,我们想说位置 X 中的用户 A 具有特殊角色,但位置 Y 中的同一用户具有其他角色。 (使用 .net 核心)
【问题讨论】:
标签: c# asp.net-core-mvc asp.net-core-identity
查看以下内容:
public class ApplicationUserRole : IdentityUserRole<string>
{
public virtual ApplicationUser User { get; set; }
public virtual ApplicationRole Role { get; set; }
public string MyProperty { get; set; }
}
参考here
【讨论】:
如果你想让一个用户拥有多个角色,你可以添加一个继承IdentityRole的ApplicationRole类,并将ApplicationUser和ApplicationRole之间的关系更改为一对多 strong>,请参考以下内容:
ApplicationRole 类
public class ApplicationRole:IdentityRole
{
public string Location { get; set; }//add the stuff you want
public ApplicationUser ApplicationUser { get; set; }
}
ApplicationUser 类
public class ApplicationUser:IdentityUser
{
public List<ApplicationRole> ApplicationRoles { get; set; }
}
在 Fluent API 中配置一对多关系
public DbSet<ApplicationUser> ApplicationUser { get; set; }
public DbSet<ApplicationRole> ApplicationRole { get; set; }
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<ApplicationUser>()
.HasMany(u => u.ApplicationRoles)
.WithOne(r => r.ApplicationUser);
}
【讨论】:
除了更改角色表之外,还有一个用于这些自定义的特殊表,称为用户声明表。在这里,您可以为用户分配新的和不同的属性。角色只是 ASP.NET Core Identity 中的另一个用户声明,将在后台自动转换为用户声明。定义一个新的用户声明 (companyB, attrX), (companyA, attrZ)。然后定义一个新的授权策略供它使用。 这里有一些关于user-claims和custom policies的官方文档。
【讨论】: