【问题标题】:Using a Custom UserStore and RoleStore in ASP.NET 5在 ASP.NET 5 中使用自定义 UserStore 和 RoleStore
【发布时间】:2016-08-20 09:36:06
【问题描述】:

我已经为使用 ASP.NET 5、MVC 6、EF 7 和 Identity 3 的项目实现了自定义 RoleStore 和自定义 UserStore。但是 - 我不太清楚如何配置身份以使用我的自定义 RoleStore 和自定义 UserStore 而不是通常的产品。如何重新配置​​系统以使用我的自定义类?

PS:我也有自定义的用户和角色类。

解决方案

这就是我最终要做的。首先,我从我的项目中卸载了“身份实体框架”包。这导致缺少一些东西,所以我重新实现了它们(阅读:从here 复制它们),并将它们放在“标准”命名空间中以表明它们没有被定制。我现在有一个“安全”命名空间,其中包含以下内容:

  • 标准
    • IdentityRole.cs
    • IdentityRoleClaim.cs
    • IdentityUser.cs
    • IdentityUserClaim.cs
    • IdentityUserLogin.cs
    • IdentityUserRole.cs
  • BuilderExtensions.cs
  • IdentityDbContext.cs
  • Resources.resx
  • Role.cs
  • RoleStore.cs
  • User.cs
  • UserStore.cs

以粗体显示的项目包含项目特定的功能。

允许我使用自定义商店的代码位于“BuilderExtensions”文件中,其中包含以下类:

public static class BuilderExtensions
{
    public static IdentityBuilder AddCustomStores<TContext, TKey>(this IdentityBuilder builder)
        where TContext : DbContext
        where TKey : IEquatable<TKey>
    {
        builder.Services.TryAdd(GetDefaultServices(builder.UserType, builder.RoleType, typeof(TContext), typeof(TKey)));
        return builder;
    }

    private static IServiceCollection GetDefaultServices(Type userType, Type roleType, Type contextType, Type keyType)
    {
        var userStoreType = typeof(UserStore<,,,>).MakeGenericType(userType, roleType, contextType, keyType);
        var roleStoreType = typeof(RoleStore<,,>).MakeGenericType(roleType, contextType, keyType);
        var services = new ServiceCollection();
        services.AddScoped(
            typeof(IUserStore<>).MakeGenericType(userType),
            userStoreType);
        services.AddScoped(
            typeof(IRoleStore<>).MakeGenericType(roleType),
            roleStoreType);
        return services;
    }
}

这允许我在我的 Startup.cs 文件中编写以下内容:

services.AddIdentity<User, Role>()
    .AddCustomStores<PrimaryContext, string>()
    .AddDefaultTokenProviders();

并且将使用自定义存储。请注意,PrimaryContext 是我的整个项目 DbContext 的名称。它继承自 IdentityDbContext。

讨论

我本可以保留“Identity Entity Framework”包并避免自己复制“Standard”命名空间的内容,但我选择不这样做,这样我可以使我的标识符保持简短和明确。

【问题讨论】:

    标签: c# asp.net-core-mvc entity-framework-core asp.net-identity-3


    【解决方案1】:

    查看此部分 重新配置应用程序以使用 Overview of Custom Storage Providers for ASP.NET Identity 中的新存储提供程序

    特别是“如果您的项目中包含默认存储提供程序,则必须删除默认提供程序并将其替换为您的提供程序。”

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
    {
        var manager = new ApplicationUserManager(new YourNewUserStore(context.Get<ExampleStorageContext>()));
        ...
    }
    

    【讨论】:

    • 谢谢亚当。我看过那篇文章,但重新考虑它给了我一些想法。最后,我删除了对 Identity EF 框架的引用,并实现了我自己对 IdentityBuilder 类的扩展。我必须在 Identity EF 包中实现一些类,但这并不是一个可观的代码量。我会在我的问题中添加详细信息,以便其他人将来可以找到它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-10-23
    • 2015-08-07
    • 1970-01-01
    • 2014-06-01
    • 2015-04-10
    • 2017-09-14
    • 2023-03-23
    相关资源
    最近更新 更多