如何在 aspnet core 身份中添加多个身份存储?

How to add more than one identity store in aspnet core identity?

我目前正在向 IdentityServer4 添加 ASP.NET Core Identity。

我添加了类似于下面一行的标识。

services.AddDbContext<PublicApplicationDbContext>(options =>
                options.UseSqlServer(
                    connection))
                .AddIdentity<PublicIdentityUser, PublicIdentityRole>(opts =>
                {
                    opts.Password.RequiredLength = 6;
                })
                .AddDefaultTokenProviders()
                .AddEntityFrameworkStores<PublicApplicationDbContext>();

我想要一个类似的存储库,所以我创建了一组单独的内部对象,如 InternalApplicationDbContext、InternalIdentityUser。我认为这就像配置上述步骤并注入这个一样简单...

UserManager<InternalIdentityUser>

但是,它似乎不起作用,我收到了与此类似的错误。 方案已经存在 https://github.com/aspnet/AspNetCore.Docs/issues/8223

我已经阅读了一些与此相关的文档,但没有任何迹象表明它支持多个身份提供者。是这种情况还是我遗漏了什么?

总而言之,我想要两个单独的数据库来管理用户,一个用于 public 用户,另一个用于内部用户。我想使用内置身份 API UserManager 来封装实现,因为老实说我不想构建自己的。

https://docs.microsoft.com/en-us/aspnet/core/security/authentication/identity-custom-storage-providers?view=aspnetcore-2.2#references

查看 github 上的 ASP.NET 核心源代码后,可以使用此扩展方法添加第二个身份:

using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using System;
using System.Collections.Generic;
using System.Text;

namespace Whatever
{
    public static class IdentityExtensions
    {
        public static IdentityBuilder AddSecondIdentity<TUser, TRole>(
            this IServiceCollection services)
            where TUser : class
            where TRole : class
        {
            services.TryAddScoped<IUserValidator<TUser>, UserValidator<TUser>>();
            services.TryAddScoped<IPasswordValidator<TUser>, PasswordValidator<TUser>>();
            services.TryAddScoped<IPasswordHasher<TUser>, PasswordHasher<TUser>>();
            services.TryAddScoped<IRoleValidator<TRole>, RoleValidator<TRole>>();
            services.TryAddScoped<ISecurityStampValidator, SecurityStampValidator<TUser>>();
            services.TryAddScoped<IUserClaimsPrincipalFactory<TUser>, UserClaimsPrincipalFactory<TUser, TRole>>();
            services.TryAddScoped<UserManager<TUser>, AspNetUserManager<TUser>>();
            services.TryAddScoped<SignInManager<TUser>, SignInManager<TUser>>();
            services.TryAddScoped<RoleManager<TRole>, AspNetRoleManager<TRole>>();

            return new IdentityBuilder(typeof(TUser), typeof(TRole), services);
        }
    }
}