Nab*_*eel 3 c# asp.net-identity asp.net-core
我正在编写 IdentityRoleManager 的扩展以允许多租户角色。角色在不同租户中可以具有相同的名称,他们可以将自己的声明分配给角色。
如何允许表中的角色名称重复?我打算通过 RoleManager 实现的每个租户的角色名称都是唯一的。
尝试了 OnModelCreating FluentApi 但它没有像 EF6 那样提供对象作为注释传递
builder.Entity().ToTable("PenRoles") .Property(p => p.Name).HasAnnotation("Index", new _____{ });
怎么做?
小智 6
更改角色 Fluent api 配置:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
然后重写 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;
}
}
Run Code Online (Sandbox Code Playgroud)
然后注册到 DI 容器并更改启动文件中的 ASP Net Identity 配置以使用此类:
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;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1600 次 |
最近记录: |