【问题标题】:Extending IdentityRole and IdentityUser扩展 IdentityRole 和 IdentityUser
【发布时间】:2014-02-27 01:43:58
【问题描述】:

我正在使用 ASPNet Identity 在我的 Web 应用程序中实现安全性。

有一个要求,我需要扩展 IdentityRole 和 IdentityUser。

这是我扩展 IdentityUser 的代码。

public class ApplicationUser : IdentityUser
{
    public virtual User  User { get; set; }
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("name=CoreContext")
    {
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Entity<IdentityUser>()
            .ToTable("AspNetUsers");
        modelBuilder.Entity<ApplicationUser>()
            .ToTable("AspNetUsers");
    }
}

我唯一的问题是身份角色

【问题讨论】:

  • 而你的问题/问题是......究竟是什么?请更详细地更新您的问题。
  • 我的问题是我无法扩展 IdentityRole。
  • @RamonCruz - 谁说你不能扩展 IdentityRole?

标签: asp.net-mvc-5 asp.net-identity


【解决方案1】:

要扩展 User ,请将您的 ApplicationUser 类(位于 IdentityModels.cs)更新为

public class ApplicationUser : IdentityUser
{
    public async Task<ClaimsIdentity> 
        GenerateUserIdentityAsync(UserManager<ApplicationUser> manager)
    {
        var userIdentity = await manager
            .CreateIdentityAsync(this, 
                DefaultAuthenticationTypes.ApplicationCookie);
        return userIdentity;
    }

    public string Address { get; set; }
    public string City { get; set; }
    public string State { get; set; }

    // Use a sensible display name for views:
    [Display(Name = "Postal Code")]
    public string PostalCode { get; set; }

}

要扩展角色,创建一个类ApplicationRole.cs

public class ApplicationRole : IdentityRole
{
    public ApplicationRole() : base() { }
    public ApplicationRole(string name) : base(name) { }
    public string Description { get; set; }
}

并在IdentityConfig.cs文件中添加类:

public class ApplicationRoleManager : RoleManager<ApplicationRole>
{
    public ApplicationRoleManager(
        IRoleStore<ApplicationRole,string> roleStore)
        : base(roleStore)
    {
    }
    public static ApplicationRoleManager Create(
        IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
    {
        return new ApplicationRoleManager(
            new RoleStore<ApplicationRole>(context.Get<ApplicationDbContext>()));
    }
}

现在清除旧数据库,运行应用程序并注册用户。它将在 AspNetUsers 表中再创建 3 个字段(地址、城市、州),在 AspNetRoles 表中再创建一个字段(描述)。就是这样。

欲了解更多信息,请访问网站: Extending Identity Role

【讨论】:

  • 嗨,您是否暗示了多租户,我在扩展 roles 上的属性时遇到问题
  • 如何在 Asp.Net Core 3.1 中做到这一点?没有IdentityConfig.cs这样的文件...
  • @Stian Core ,我不认为你可以这样做。
【解决方案2】:

您可以在您的应用程序中从 IdentityRole 继承,就像您使用 IdentityUser 一样。为什么需要扩展 IdentityRole? 请查看以下文章,该文章详细解释了您要执行的操作http://typecastexception.com/post/2014/02/13/ASPNET-MVC-5-Identity-Extending-and-Modifying-Roles.aspx

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-06
    • 2021-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多