如何使用Web API 2 + AspNet Identity 2扩展IdentityRole

独山佩雷拉

我正在尝试扩展最新版本的Visual Studio 2013中的Web API 2(带有个人帐户)模板中提供的AspNet IdentityRole类。当我按/ api / roles时,它将返回一个空数组

身份模型

namespace API.Models
{
// You can add profile data for the user by adding more properties to your ApplicationUser class, please visit http://go.microsoft.com/fwlink/?LinkID=317594 to learn more.
public class ApplicationUser : IdentityUser<string, IdentityUserLogin, ApplicationUserRole, IdentityUserClaim>, IUser, IUser<string>
{
    [NotMapped]
    public virtual UserProfile Profile { get; set; }

    public virtual ICollection<ApplicationUserRole> UserRoles { get; set; }

    //public virtual List<ApplicationUserRole> ApplicationRoles { get; set; }

    public async Task<ClaimsIdentity> GenerateUserIdentityAsync(UserManager<ApplicationUser> manager,
        string authenticationType)
    {
        // Note the authenticationType must match the one defined in CookieAuthenticationOptions.AuthenticationType
        ClaimsIdentity userIdentity = await manager.CreateIdentityAsync(this, authenticationType);
        // Add custom user claims here
        return userIdentity;
    }
}

public class ApplicationRole : IdentityRole<string, ApplicationUserRole>
{
    public ApplicationRole() : base() { }

}

public class ApplicationUserRole : IdentityUserRole<string>
{
    public ApplicationUserRole()
        : base()
    { }

    public virtual ApplicationRole Role { get; set; }
}

public class ApplicationDbContext : IdentityDbContext<ApplicationUser,ApplicationRole,string,IdentityUserLogin,ApplicationUserRole,IdentityUserClaim> 

{

     public ApplicationDbContext()
        : base("DefaultConnection")
    {
        base.Configuration.ProxyCreationEnabled = false;
    }

     public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
}

}

身份配置

namespace API
{
// Configure the application user manager used in this application. UserManager is defined in ASP.NET Identity and is used by the application.

public class ApplicationUserManager : UserManager<ApplicationUser, string>
{
    public ApplicationUserManager(IUserStore<ApplicationUser> store)
        : base(store)
    {
    }

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options,
        IOwinContext context)
    {
        var manager = new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<ApplicationDbContext>()));

        // Configure validation logic for usernames
        manager.UserValidator = new UserValidator<ApplicationUser>(manager)
        {
            AllowOnlyAlphanumericUserNames = false,
            RequireUniqueEmail = true
        };
        // Configure validation logic for passwords
        manager.PasswordValidator = new PasswordValidator
        {
            RequiredLength = 6,
            RequireNonLetterOrDigit = true,
            RequireDigit = true,
            RequireLowercase = true,
            RequireUppercase = true,
        };
        IDataProtectionProvider dataProtectionProvider = options.DataProtectionProvider;
        if (dataProtectionProvider != null)
        {
            manager.UserTokenProvider =
                new DataProtectorTokenProvider<ApplicationUser>(dataProtectionProvider.Create("ASP.NET Identity"));
        }
        return manager;
    }
}



public class ApplicationRoleManager : RoleManager<ApplicationRole, string>
{
    public ApplicationRoleManager(IRoleStore<ApplicationRole, string> store)
        : base(store)
    {
    }

    public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options,
        IOwinContext context)
    {
        var manager = new ApplicationRoleManager(new RoleStore<ApplicationRole>(context.Get<ApplicationDbContext>()));
        return manager;
    }

}

}

艾斯卡·亨德拉(Aiska Hendra)

你的错误在这里

ApplicationDbContext : IdentityDbContext<ApplicationUser>

您的分贝上下文是从程度IdentityDbContext<ApplicationUser>这是从基

IdentityDbContext<TUser, IdentityRole, string, IdentityUserLogin, IdentityUserRole, IdentityUserClaim>

IdentityRole实际上,在实际需要ApplicationRole您的角色生成ApplicationDbContext

将您的ApplicationDbContext更改为

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string, IdentityUserLogin, ApplicationUserRole, IdentityUserClaim>
{

 public ApplicationDbContext()
    : base("DefaultConnection", false)
 {
    base.Configuration.ProxyCreationEnabled = false;
 }

 public static ApplicationDbContext Create()
 {
    return new ApplicationDbContext();
 }
}

您此时不必覆盖OnModelCreating并添加属性Roles。

由于您在ApplicationUserRole中具有导航属性,因此应添加configurationmapping

protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
{
    base.OnModelCreating(modelBuilder);
    modelBuilder.Entity<ApplicationUserRole>().HasRequired(ur => ur.Role).WithMany().HasForeignKey(ur => ur.RoleId);
}

IdentityModel.cs应该像这样:

public class ApplicationUserRole : IdentityUserRole<string>
{
    public ApplicationUserRole()
        : base()
    { }

    public virtual ApplicationRole Role { get; set; }
}

public class ApplicationRole : IdentityRole<string, ApplicationUserRole>
{
    public ApplicationRole() : base() { }

    public ApplicationRole(string name, string description)
        : base()
    {
        this.Name = name;
        this.Description = description;
    }

    public string Description { get; set; }
}

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

public class ApplicationDbContext : IdentityDbContext<ApplicationUser, ApplicationRole, string, IdentityUserLogin, ApplicationUserRole, IdentityUserClaim>
{

    public ApplicationDbContext()
        : base("DefaultConnection")
    {
        base.Configuration.ProxyCreationEnabled = false;
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }
    protected override void OnModelCreating(System.Data.Entity.DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
        modelBuilder.Entity<ApplicationUserRole>().HasRequired(ur => ur.Role).WithMany().HasForeignKey(ur => ur.RoleId);
    }
}

identityconfig.cs应该是这样的:

public class ApplicationUserStore : UserStore<ApplicationUser, ApplicationRole, string, IdentityUserLogin, ApplicationUserRole, IdentityUserClaim>, IUserStore<ApplicationUser>
{
    public ApplicationUserStore(ApplicationDbContext context)
        : base(context)
    {
    }   
}

public class ApplicationUserManager : UserManager<ApplicationUser>
{
    public ApplicationUserManager(IUserStore<ApplicationUser> store)
        : base(store)
    {
    }

    public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options, IOwinContext context) 
    {
        var manager = new ApplicationUserManager(new ApplicationUserStore(context.Get<ApplicationDbContext>()));
        ....
    }
}
public class ApplicationRoleStore : RoleStore<ApplicationRole, string, ApplicationUserRole>
{
    public ApplicationRoleStore(ApplicationDbContext context)
        : base(context)
    {

    }
}
public class ApplicationRoleManager : RoleManager<ApplicationRole, string>
{
    public ApplicationRoleManager(IRoleStore<ApplicationRole, string> store)
        : base(store)
    {
    }

    public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options,
        IOwinContext context)
    {
        var manager = new ApplicationRoleManager(new ApplicationRoleStore(context.Get<ApplicationDbContext>()));
        return manager;
    }
}

本文收集自互联网,转载请注明来源。

如有侵权,请联系[email protected] 删除。

编辑于
0

我来说两句

0条评论
登录后参与评论

相关文章

来自分类Dev

如何扩展Microsoft.AspNet.Identity.EntityFramework.IdentityRole

来自分类Dev

如何使用Aspnet Identity Framework v2进行程序化登录?

来自分类Dev

使用Asp.Net Identity 2将用户添加到角色后,如何使.AspNet.ApplicationCookie无效?

来自分类Dev

使用NHibernate.AspNet.Identity

来自分类Dev

使用承载令牌的MVC 5 Identity 2和Web API 2授权和调用api

来自分类Dev

使用Identity 2在Web API 2中确认电子邮件的最佳方法是什么?

来自分类Dev

使用Identity 2在Web API 2中确认电子邮件的最佳方法是什么?

来自分类Dev

使用JwtBearerAuthentication在aspnet5 rc1 Web API2标识3中发出刷新令牌

来自分类Dev

WSO2 API Manager使用Identity Server存储访问

来自分类Dev

正确使用Microsoft.AspNet.Identity 2.0

来自分类Dev

UserManager在ASPNET Identity 2应用程序中始终为null

来自分类Dev

更新到AspNet Identity版本2后无法建立或迁移数据库

来自分类Dev

如何配置 WSO2 API Manager 2.1.0 以使用 Identity Server 5.4.1

来自分类Dev

如何在域模型中使用AspNet.Identity

来自分类Dev

如何在域模型中使用AspNet.Identity

来自分类Dev

使用WSO2 Identity Server和WSO2 API Manager保护后端

来自分类Dev

使用ASP.NET Identity和ASP.NET Web API 2的基于跨域令牌的身份验证

来自分类Dev

如何扩展asp.net Web API 2用户?

来自分类Dev

无法在MVC5 Microsoft.AspNet.Identity.EntityFramework.IdentityRole中添加新角色?

来自分类Dev

ASP Identity 2 + Web API令牌认证-持久声明未加载

来自分类Dev

在 Web Api 2 中获取 HttpContext.Current.User.Identity.Name null 通过 angular 4 登录

来自分类Dev

Microsoft.Aspnet.Identity.Core中使用什么设计模式?

来自分类Dev

如何在Web API中使用“ User.Identity.IsAuthenticated”

来自分类Dev

如何在Web API中使用“ User.Identity.IsAuthenticated”

来自分类Dev

如何使用 Identity Server 3 保护 Web api

来自分类Dev

Web API 2:如何搜索

来自分类Dev

受Azure保护的Aspnet核心Web API

来自分类Dev

如何在Web API 2中从静态类使用StructureMap?

来自分类Dev

如何在 Web API v2 中使用参数?

Related 相关文章

  1. 1

    如何扩展Microsoft.AspNet.Identity.EntityFramework.IdentityRole

  2. 2

    如何使用Aspnet Identity Framework v2进行程序化登录?

  3. 3

    使用Asp.Net Identity 2将用户添加到角色后,如何使.AspNet.ApplicationCookie无效?

  4. 4

    使用NHibernate.AspNet.Identity

  5. 5

    使用承载令牌的MVC 5 Identity 2和Web API 2授权和调用api

  6. 6

    使用Identity 2在Web API 2中确认电子邮件的最佳方法是什么?

  7. 7

    使用Identity 2在Web API 2中确认电子邮件的最佳方法是什么?

  8. 8

    使用JwtBearerAuthentication在aspnet5 rc1 Web API2标识3中发出刷新令牌

  9. 9

    WSO2 API Manager使用Identity Server存储访问

  10. 10

    正确使用Microsoft.AspNet.Identity 2.0

  11. 11

    UserManager在ASPNET Identity 2应用程序中始终为null

  12. 12

    更新到AspNet Identity版本2后无法建立或迁移数据库

  13. 13

    如何配置 WSO2 API Manager 2.1.0 以使用 Identity Server 5.4.1

  14. 14

    如何在域模型中使用AspNet.Identity

  15. 15

    如何在域模型中使用AspNet.Identity

  16. 16

    使用WSO2 Identity Server和WSO2 API Manager保护后端

  17. 17

    使用ASP.NET Identity和ASP.NET Web API 2的基于跨域令牌的身份验证

  18. 18

    如何扩展asp.net Web API 2用户?

  19. 19

    无法在MVC5 Microsoft.AspNet.Identity.EntityFramework.IdentityRole中添加新角色?

  20. 20

    ASP Identity 2 + Web API令牌认证-持久声明未加载

  21. 21

    在 Web Api 2 中获取 HttpContext.Current.User.Identity.Name null 通过 angular 4 登录

  22. 22

    Microsoft.Aspnet.Identity.Core中使用什么设计模式?

  23. 23

    如何在Web API中使用“ User.Identity.IsAuthenticated”

  24. 24

    如何在Web API中使用“ User.Identity.IsAuthenticated”

  25. 25

    如何使用 Identity Server 3 保护 Web api

  26. 26

    Web API 2:如何搜索

  27. 27

    受Azure保护的Aspnet核心Web API

  28. 28

    如何在Web API 2中从静态类使用StructureMap?

  29. 29

    如何在 Web API v2 中使用参数?

热门标签

归档