扩展IdentityRole和IdentityUser

时间:2014-02-27 01:43:58

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

我正在使用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

2 个答案:

答案 0 :(得分:5)

要扩展用户,请将您的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个字段(Address,City,State),并在AspNetRoles表中再创建一个字段(Description)。就是这样。

有关详细信息,请访问该网站: Extending Identity Role

答案 1 :(得分:4)

您可以使用与IdentityUser相同的方式从应用程序中继承IdentityRole。为什么需要扩展IdentityRole? 请查看以下文章,其中详细说明了您要执行的操作http://typecastexception.com/post/2014/02/13/ASPNET-MVC-5-Identity-Extending-and-Modifying-Roles.aspx