【问题标题】:Adding Identity 2.0 Roles to custom Identity将 Identity 2.0 角色添加到自定义身份
【发布时间】:2015-05-11 17:48:33
【问题描述】:

我最近开始使用 MVC 5 和 Identity 2.0 开发一个新应用程序,为了使用不同的密码哈希算法,我实现了本指南中详述的自定义身份 (https://code.msdn.microsoft.com/ASPNET-45-MVC5-Custom-1a94ab26#content)。

我已经研究了将角色合并到此身份实现中的各种方法,但到目前为止还没有找到使它们与此新身份实现一起使用的方法。

现在有人知道如何将角色添加到类似的自定义身份提供者吗?

非常感谢任何指导。

【问题讨论】:

  • 该教程毫无价值,因为您真正需要做的就是在对象上实现此接口并将其提供给 UserManager。 msdn.microsoft.com/en-us/library/…
  • 感谢您的建议,我现在使用实现 IPasswordHasher 的自定义密码散列器

标签: c# asp.net-mvc-5 asp.net-identity-2 user-roles


【解决方案1】:

IdentityUser(ApplicationUser:如果您使用标准模板)的实现将提供将用户与角色相关联的方法:AddToRoleAsync、AddToRolesAsync、GetRolesAsync、RemoveFromRolesAsync。

如果你想管理角色,我怀疑,你必须添加一个RoleManager<IdentityRole>。

public class ApplicationRoleManager : RoleManager<IdentityRole>
    {
        public ApplicationRoleManager(IRoleStore<IdentityRole, string> roleStore)
            : base(roleStore)
        {
        }

        public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
        {
            var appRoleManager = new ApplicationRoleManager(new RoleStore<IdentityRole>(context.Get<ApplicationDbContext>()));

            return appRoleManager;
        }
    }

并将其添加到 owin 上下文中:

app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);

ApplicationRoleManager 将允许您创建角色 (CreateAsync)、查找 (FindByIdAsync)、删除 (DeleteAsync)。

而您的 ApplicationUserManager:

public class ApplicationUserManager : UserManager<ApplicationUser>
{
  ...
}

将允许您将角色与用户 (AddToRoleAsync) 关联,删除 (RemoveFromRoleAsync)。

如果您已经使用接口IUserStore 实现了您的UserStore,那么您还需要实现IUserRoleStore。

在最后一个界面中,您可以找到AddToRoleAsync、GetRolesAsync、IsInRoleAsync、RemoveFromRoleAsync。

您还必须实现 RoleStore (IRoleStore)。

如果你想阅读一些关于这个主题的好文章,我建议你看看这个blog。 到目前为止,这个人已经写了 4 篇关于 ASP.NET Identity 2.x 的文章:

Part 1
Part 2
Part 3
Part 4(你感兴趣的那个)

这是另一个guy,他在这个话题上写了一些有趣的东西。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-08
    • 2018-09-05
    • 2014-01-23
    • 1970-01-01
    • 2019-01-27
    • 2021-02-02
    • 1970-01-01
    相关资源
    最近更新 更多