Asp.Net身份和多租户上的角色名称重复 [英] Duplicate Role Names on Asp.Net Identity and Multi-tenancy

查看:117
本文介绍了Asp.Net身份和多租户上的角色名称重复的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用ASP.Net MVC和Identity 2.0开发多租户Web应用程序.我已经这样扩展了IdentityRole:

I'm developing a Multi-tenancy web application with ASP.Net MVC and Identity 2.0. I have extended the IdentityRole like this:

public class ApplicationRole : IdentityRole
{
    public ApplicationRole() : base() { }
    public ApplicationRole(string name) : base(name) { }

    public string TenantId { get; set; }
}

这是因为每个租户都有各自的角色集,例如管理员",工作人员"等.

This because each Tenant will have individual sets of roles, like "Admin", "Staff", etc.

但是问题是,当我添加一个新角色时,如果租户A"具有管理员"角色,则当我向租户B"中添加管理员"角色时,我会收到一个IdentityResult错误,因为管理员"名称被采用...这很明显,因为AspNetRoles表上的名称"字段是唯一的...

But the problem is, when I add a new Role, if the "Tenant A" has "Admin" role, when I add to "Tenant B" the "Admin" role, I get an IdentityResult error because "Admin" name is taken... Its is kinda obvious because the "Name" field on the AspNetRoles table is Unique...

IdentityResult roleResult = await RoleManager.CreateAsync(
  new ApplicationRole
  {
    Name = "Admin",
    TenantId = GetTenantId()
  });

但是接下来我如何自定义ASP.Net身份,以便"AspNetRoles"中的名称"字段可以与"TenantId"一起唯一,而不是单独?我发现了有关扩展IdentityRole的信息(就像我确实添加了一个字段一样),但没有有关更改或替换它的信息...

But then how I can customize ASP.Net Identity so the "Name" field in the "AspNetRoles" can be unique with "TenantId", and not alone? I found info about extend the IdentityRole (like I did adding a field), but not about change it or replace it...

推荐答案

只需更改ApplicationDbContextOnModelCreating方法上的数据库架构,如下所示:

Simply alter database's schema on ApplicationDbContext's OnModelCreating method like this:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);

    var role = modelBuilder.Entity<IdentityRole>()
        .ToTable("AspNetRoles");
    role.Property(r => r.Name)
        .IsRequired()
        .HasMaxLength(256)
        .HasColumnAnnotation("Index", new IndexAnnotation(
            new IndexAttribute("RoleNameIndex") 
            { IsUnique = false }));
}

但是您还必须自定义RoleValidator类.因为默认角色验证程序会使重复的角色名称无效.

But you must customize RoleValidator class also. Because default role validator invalidates duplicated role names.

public class MyRoleValidator:RoleValidator<ApplicationRole>
{
     public override async Task<IdentityResult> ValidateAsync(ApplicationRole item)
     {
         // implement your validation logic here

         return IdentityResult.Success;
     }
}

现在,每次创建角色管理器时,都必须设置角色验证器.

Now every time you create the role manager you must set the role validator.

roleManager.RoleValidator=new MyRoleValidator();

这篇关于Asp.Net身份和多租户上的角色名称重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆