.net Identity 2.0不返回角色

时间:2016-03-24 20:31:33

标签: c# asp.net .net asp.net-web-api2 asp.net-identity-2

我已经使用本教程http://bitoftech.net/2014/06/01/token-based-authentication-asp-net-web-api-2-owin-asp-net-identity/来了解.net身份会员平台的介绍......我得到了它并运行正常。但是,我去扩展我的角色,现在我进行身份验证后,没有返回任何角色(只有一个空数组)...请参阅下面的代码:

  • IdentityConfig.cs

    public class ApplicationUserManager : UserManager<ApplicationUser>
    {
        public ApplicationUserManager(IUserStore<ApplicationUser> store)
           : base(store)
        {}
        public static ApplicationUserManager Create(IdentityFactoryOptions<ApplicationUserManager> options,
        IOwinContext context)
        {
             return new ApplicationUserManager(new UserStore<ApplicationUser>(context.Get<AuthContext>()));
        }
    }
    
    public class ApplicationRoleManager : RoleManager<ApplicationRole>
    {
        public ApplicationRoleManager(IRoleStore<ApplicationRole, string> roleStore)
           : base(roleStore)
        {}
    
    public static ApplicationRoleManager Create(IdentityFactoryOptions<ApplicationRoleManager> options, IOwinContext context)
    {
        var manager = new ApplicationRoleManager(
                    new RoleStore<ApplicationRole>(context.Get<AuthContext>()));
        return manager;
    }
    }
    
  • Startup.cs

    public void Configuration(IAppBuilder app)
    {
        ConfigureOAuth(app);
        HttpConfiguration config = new HttpConfiguration();        
        WebApiConfig.Register(config);
        app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
        app.UseWebApi(config);
    }
    
    public void ConfigureOAuth(IAppBuilder app)
    {
        // Configure the db context, user manager and role manager to use a single instance per request
        app.CreatePerOwinContext(AuthContext.Create);
        app.CreatePerOwinContext<ApplicationUserManager>(ApplicationUserManager.Create);
        app.CreatePerOwinContext<ApplicationRoleManager>(ApplicationRoleManager.Create);
        //app.CreatePerOwinContext<ApplicationSignInManager>(ApplicationSignInManager.Create);
    
        OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
        {
            AllowInsecureHttp = true,
            TokenEndpointPath = new PathString("/Token"),
            AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
            Provider = new SimpleAuthorizationServerProvider(),
            RefreshTokenProvider = new SimpleRefreshTokenProvider()
        };
    
        // Token Generation
        app.UseOAuthAuthorizationServer(OAuthServerOptions);
        app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
    
    }
    
  • AuthRepository.cs

    private AuthContext _ctx;
    
    private ApplicationUserManager _userManager;
    
    public AuthRepository()
    {
        _ctx = new AuthContext();
        _userManager = new ApplicationUserManager(new UserStore<ApplicationUser>(_ctx));
    }
    
    public async Task<IdentityResult> RegisterUser(UserModel userModel)
    {
        ApplicationUser user = new ApplicationUser
        {
            UserName = userModel.UserName
        };
    
        var result = await _userManager.CreateAsync(user, userModel.Password);
    
        return result;
    }
    
    public async Task<ApplicationUser> FindUser(string userName, string password)
    {
        ApplicationUser user = await _userManager.FindAsync(userName, password);
    
        return user;
    }
    
    public Client FindClient(string clientId)
    {
        var client = _ctx.Clients.Find(clientId);
    
        return client;
    }
    
    public async Task<bool> AddRefreshToken(RefreshToken token)
    {
    
        var existingToken = _ctx.RefreshTokens.Where(r => r.Subject == token.Subject && r.ClientId == token.ClientId).SingleOrDefault();
    
        if (existingToken != null)
        {
            var result = await RemoveRefreshToken(existingToken);
        }
    
        _ctx.RefreshTokens.Add(token);
    
        return await _ctx.SaveChangesAsync() > 0;
    }
    
    public async Task<bool> RemoveRefreshToken(string refreshTokenId)
    {
        var refreshToken = await _ctx.RefreshTokens.FindAsync(refreshTokenId);
    
        if (refreshToken != null)
        {
            _ctx.RefreshTokens.Remove(refreshToken);
            return await _ctx.SaveChangesAsync() > 0;
        }
    
        return false;
    }
    
    public async Task<bool> RemoveRefreshToken(RefreshToken refreshToken)
    {
        _ctx.RefreshTokens.Remove(refreshToken);
        return await _ctx.SaveChangesAsync() > 0;
    }
    
    public async Task<RefreshToken> FindRefreshToken(string refreshTokenId)
    {
        var refreshToken = await _ctx.RefreshTokens.FindAsync(refreshTokenId);
    
        return refreshToken;
    }
    
    public List<RefreshToken> GetAllRefreshTokens()
    {
        return _ctx.RefreshTokens.ToList();
    }
    
    public async Task<ApplicationUser> FindAsync(UserLoginInfo loginInfo)
    {
        ApplicationUser user = await _userManager.FindAsync(loginInfo);
    
        return user;
    }
    
    public async Task<IdentityResult> CreateAsync(ApplicationUser user)
    {
        var result = await _userManager.CreateAsync(user);
    
        return result;
    }
    
    public async Task<IdentityResult> AddLoginAsync(string userId, UserLoginInfo login)
    {
        var result = await _userManager.AddLoginAsync(userId, login);
    
        return result;
    }
    
    public void Dispose()
    {
        _ctx.Dispose();
        _userManager.Dispose();
    
    }
    
  • ApplicationRole.cs

    public class ApplicationRole : IdentityRole
    {
         public ApplicationRole() : base() { }
         public ApplicationRole(string name)
             : base(name)
         {}
        public virtual string Module { get; set; }
    }
    
  • ApplicationUser.cs

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

    public class AuthContext : IdentityDbContext<ApplicationUser>
    {
    new public DbSet<ApplicationRole> Roles { get; set; }
    
    public AuthContext()
        : base("name=AuthDBConnectionString")
    {
      //  Database.SetInitializer<AuthContext>(null);
    }
    
    public DbSet<Client> Clients { get; set; }
    public DbSet<RefreshToken> RefreshTokens { get; set; }
    
    static AuthContext()
    {
        // Set the database intializer which is run once during application start
        // This seeds the database with admin user credentials and admin role
        Database.SetInitializer<AuthContext>(new AuthInitializer());
    }
    
    public static AuthContext Create()
    {
        return new AuthContext();
    }
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        if (modelBuilder == null)
        {
            throw new ArgumentNullException("modelBuilder");
        }
    
        // Keep this:
        modelBuilder.Entity<IdentityUser>().ToTable("AspNetUsers");
    
        // Change TUser to ApplicationUser everywhere else - 
        // IdentityUser and ApplicationUser essentially 'share' the AspNetUsers Table in the database:
        EntityTypeConfiguration<ApplicationUser> table =
            modelBuilder.Entity<ApplicationUser>().ToTable("AspNetUsers");
    
        table.Property((ApplicationUser u) => u.UserName).IsRequired();
    
        // EF won't let us swap out IdentityUserRole for ApplicationUserRole here:
      //  modelBuilder.Entity<ApplicationUser>().HasMany<IdentityUserRole>((ApplicationUser u) => u.Roles);
        modelBuilder.Entity<IdentityUserRole>().HasKey((IdentityUserRole r) =>
            new { UserId = r.UserId, RoleId = r.RoleId }).ToTable("AspNetUserRoles");
    
        // Leave this alone:
        EntityTypeConfiguration<IdentityUserLogin> entityTypeConfiguration =
            modelBuilder.Entity<IdentityUserLogin>().HasKey((IdentityUserLogin l) =>
                new
                {
                    UserId = l.UserId,
                    LoginProvider = l.LoginProvider,
                    ProviderKey
                        = l.ProviderKey
                }).ToTable("AspNetUserLogins");
    
    
        EntityTypeConfiguration<IdentityUserClaim> table1 =
            modelBuilder.Entity<IdentityUserClaim>().ToTable("AspNetUserClaims");
    
    
    
        // Add this, so that IdentityRole can share a table with ApplicationRole:
        modelBuilder.Entity<IdentityRole>().ToTable("AspNetRoles");
    
        // Change these from IdentityRole to ApplicationRole:
        EntityTypeConfiguration<ApplicationRole> entityTypeConfiguration1 =
            modelBuilder.Entity<ApplicationRole>().ToTable("AspNetRoles");
    
        entityTypeConfiguration1.Property((ApplicationRole r) => r.Name).IsRequired();
    }
    
  • 在下面的行中,如果我将ApplicationRole更改为IdentityRole,那么它似乎可以将角色拉回来,但是我需要添加一个&#39;模块&#39;在ApplicationRole.cs上面找到的属性

            // Change these from IdentityRole to ApplicationRole:
        EntityTypeConfiguration<ApplicationRole> entityTypeConfiguration1 =
            modelBuilder.Entity<ApplicationRole>().ToTable("AspNetRoles");
    
        entityTypeConfiguration1.Property((ApplicationRole r) => r.Name).IsRequired();
    

不确定我在这里做错了什么......任何帮助都将不胜感激! 感谢

1 个答案:

答案 0 :(得分:2)

您需要删除这些行

    // Change these from IdentityRole to ApplicationRole:
//EntityTypeConfiguration<ApplicationRole> entityTypeConfiguration1 =
   // modelBuilder.Entity<ApplicationRole>().ToTable("AspNetRoles");

//entityTypeConfiguration1.Property((ApplicationRole r) => r.Name).IsRequired();

然后在其位置添加

  base.OnModelCreating(modelBuilder);

你仍然会使用ApplicationRole将你的表作为AspNetRoles和AspNetUsers,因为它是从IdentityRole继承的