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

时间:2019-05-14 04:31:39

标签: c# .net-core asp.net-identity identityserver4

我目前正在使用IdentityServer4添加ASP.NET Core身份。

我添加了与以下行类似的身份。

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

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

总而言之,我希望使用两个独立的数据库来管理用户,一个用于公共用户,另一个用于内部数据库。我真的想使用内置的身份API UserManager来封装实现,因为我真的不想构建自己的。

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

1 个答案:

答案 0 :(得分:0)

在github上浏览ASP.NET Core源代码后,可以使用此扩展方法添加第二个标识:

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);
        }
    }
}

https://stackoverflow.com/a/47434573/8006943

相关问题