授权和GetRoles不ASP.NET身份工作 [英] Authorize and GetRoles doesn't work in ASP.NET Identity

查看:252
本文介绍了授权和GetRoles不ASP.NET身份工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ASP.NET身份2.1.0使用实体框架的实现。结果
认证工作正常,但基于角色的安全性有问题。
虽然我已经添加角色给用户,但这code返回空:

I am using ASP.NET Identity 2.1.0 using Entity Framework implementation.
Authentication works fine but role based security has problem. Although I've added role to the user but this code returns empty :

  var roles= UserManager.GetRoles(User.Identity.GetUserId());

另外授权基于角色的登录的用户失败。当用户重定向到类似下面的应用重定向他到登录页面的控制器。

Also Authorization based on roles of logged in user fails. when user redirects to a controller like below application redirects him to the login page.

  [Authorize(Roles = "Admin")]
    public abstract partial class AdminAreaController : Controller
    {

为了增加ASP.NET身份,首先,我创建自定义的用户类添加会员数据:

In order to add ASP.NET Identity, first, I have created custom user class to add profile data :

    public class BasemapUser : IdentityUser
{
    [MaxLength(100)]
    public string Name { get; set; }

    [MaxLength(100)]
    public string CompanyName { get; set; }

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

这是的DbContext类:

This is DbContext class :

    public class WebCoreMapDbContext : IdentityDbContext<BasemapUser>
{
    public WebDbContext()
        : base("WebDbContext")
    {
    }

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


    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
       modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId);
       modelBuilder.Entity<IdentityUserRole>().HasKey(r => new {r.RoleId, r.UserId});
    }
}

我使用EF迁移电力shell命令创建的数据库。我看到IdentityUserRoles表中的两列外,我还没有ASP.NET身份的其他样本中看到

I created database using EF Migration commands in power shell. I see two extra columns in IdentityUserRoles table which I haven't seen in other samples of ASP.NET identity

我用这个code以添加默认的admin用户和角色:

I used this code to add default admin user and role:

        public static void Start()
    {
        var userManager = HttpContext.Current.GetOwinContext().GetUserManager<BasemapUserManager>();
        var roleManager = HttpContext.Current.GetOwinContext().Get<ApplicationRoleManager>();
        const string name = "someEmail@gmail.com";
        const string password = "somePassword";
        const string roleName = "Admin";

        //Create Role Admin if it does not exist
        IdentityRole role = roleManager.FindByName(roleName);
        if (role == null)
        {
            role = new IdentityRole(roleName);
            IdentityResult roleresult = roleManager.Create(role);
        }

        BasemapUser user = userManager.FindByName(name);
        if (user == null)
        {
            user = new BasemapUser {UserName = name, Email = name};
            IdentityResult result = userManager.Create(user, password);
            result = userManager.SetLockoutEnabled(user.Id, false);
        }

        // Add user admin to Role Admin if not already added
        IList<string> rolesForUser = userManager.GetRoles(user.Id);
        if (!rolesForUser.Contains(role.Name))
        {
            IdentityResult result = userManager.AddToRole(user.Id, role.Name);

        }
    }

管理员用户和角色已存储在数据库成功,但在IdentityUserRoles表的存储记录包含空值:

Admin user and role have been stored in database successfully but stored record in IdentityUserRoles table contains null value :

为什么GetRoles返回任何对谁在数据库中该角色的用户?也如预期其他API如IsInRole不起作用。是不是因为里面添加IdentityUserRoles表的外键?
结果

Why GetRoles returns nothing for the user who has that role in database? also other APIs like IsInRole doesn't work as expected. Is it because foreign keys which added to IdentityUserRoles table?

推荐答案

的问题是它已添加到身份表不必要的列。结果

The problem was unnecessary columns which have added to Identity tables.

由于从的DbContext延伸IdentityDbContext,我得叫base.OnModelCreating自IdentityDbContext定义它映射身份类。我没有叫,在我的code这引起了问题。

Since DbContext extends from IdentityDbContext, I have to call base.OnModelCreating since the IdentityDbContext defines it for mapping Identity classes. I haven't called that in the my code which caused the issues

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
       modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId);
       modelBuilder.Entity<IdentityUserRole>().HasKey(r => new {r.RoleId, r.UserId});
    }

已更改为

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

      // modelBuilder.Entity<IdentityUserLogin>().HasKey<string>(l => l.UserId);                // do not add this
      // modelBuilder.Entity<IdentityUserRole>().HasKey(r => new {r.RoleId, r.UserId});         // do not add this
      // other mapping codes
    }

这篇关于授权和GetRoles不ASP.NET身份工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆