ASP.NET Core身份,如何重写IdentityRole名称的唯一索引?我想存储有关租户的重复名称 [英] ASP.NET Core Identity, How to override IdentityRole Name unique index? I want to store duplicate name with respect to tenant

查看:88
本文介绍了ASP.NET Core身份,如何重写IdentityRole名称的唯一索引?我想存储有关租户的重复名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写IdentityRoleManager的扩展,以允许多租户角色.在不同的租户中,角色可以是同名的,他们可以为角色分配自己的所有权.

I am writing extension of IdentityRoleManager to allow Multi-tenant roles. Where Role could be of same name in different Tenants where they can assign their own Claims to Roles.

如何在表中允许重复的角色名称?我打算通过RoleManager实现的每个租户的角色名称都是唯一的.

How to allow duplicate Role name in the table? Role names will be unique for each tenant which i am intent to implement through RoleManager.

尝试了OnModelCreating FluentApi,但它没有像EF6中那样使对象作为注释传递

Tried OnModelCreating FluentApi but it doesnt give object to pass as annotation like in EF6

builder.Entity().ToTable("PenRoles").Property(p => p.Name).HasAnnotation("Index",新的_____ {});

builder.Entity().ToTable("PenRoles") .Property(p => p.Name).HasAnnotation("Index", new _____{ });

该怎么做?

推荐答案

更改角色流利的api配置:

change role fluent api config:

public class RoleConfiguration : IEntityTypeConfiguration<Role>
{
    public void Configure(EntityTypeBuilder<Role> builder)
    {
        builder.Metadata.RemoveIndex(new[] { builder.Property(r => r.NormalizedName).Metadata });

        builder.HasIndex(r => new { r.NormalizedName, r.ApplicationId }).HasName("RoleNameIndex").IsUnique();
    }
}

然后覆盖RoleValidator:

then override RoleValidator:

public class MyRoleValidator : RoleValidator<Role>
{
    public override async Task<IdentityResult> ValidateAsync(RoleManager<Role> manager, Role role)
    {
        var roleName = await manager.GetRoleNameAsync(role);
        if (string.IsNullOrWhiteSpace(roleName))
        {
            return IdentityResult.Failed(new IdentityError
            {
                Code = "RoleNameIsNotValid",
                Description = "Role Name is not valid!"
            });
        }
        else
        {
            var owner = await manager.Roles.FirstOrDefaultAsync(x => x.ApplicationId == role.ApplicationId && x.NormalizedName == roleName);

            if (owner != null && !string.Equals(manager.GetRoleIdAsync(owner), manager.GetRoleIdAsync(role)))
            {
                return IdentityResult.Failed(new IdentityError
                {
                    Code = "DuplicateRoleName",
                    Description = "this role already exist in this App!"
                });
            }
        }
        return IdentityResult.Success;
    }
}

然后注册到DI容器并在启动文件中更改asp net identity配置以使用此类:

then register to DI container and change asp net identity config in Startup file to use this class :

    public static IServiceCollection ConfigureIdentity(this IServiceCollection services, IConfiguration configuration)
    {
        services.AddScoped<IRoleValidator<Role>, MyRoleValidator>(); //this line...
        services.AddIdentity<ApplicationUser, Role>(options =>
        {
            options.Password.RequiredLength = configuration.GetSection(nameof(IdentitySettings)).Get<IdentitySettings>().PasswordRequiredLength;
            options.Password.RequireLowercase = configuration.GetSection(nameof(IdentitySettings)).Get<IdentitySettings>().PasswordRequireLowercase;
            options.Password.RequireUppercase = configuration.GetSection(nameof(IdentitySettings)).Get<IdentitySettings>().PasswordRequireUppercase;
            options.Password.RequireNonAlphanumeric = configuration.GetSection(nameof(IdentitySettings)).Get<IdentitySettings>().PasswordRequireNonAlphanumeric;
            options.Password.RequireDigit = configuration.GetSection(nameof(IdentitySettings)).Get<IdentitySettings>().PasswordRequireDigit;
        })
            .AddRoleValidator<MyRoleValidator>() //this line ...
            .AddEntityFrameworkStores<SepidIdentityContext>()
            .AddDefaultTokenProviders();

        return services;
    }

这篇关于ASP.NET Core身份,如何重写IdentityRole名称的唯一索引?我想存储有关租户的重复名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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