【问题标题】:Asp.net identity can't add user to roleAsp.net 身份无法将用户添加到角色
【发布时间】:2017-05-16 16:07:04
【问题描述】:
    public void AddUserToRole(Guid userId, string roleName)
    {
        var userManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(DbContext));
        var user = userManager.FindById(userId.ToString());
        userManager.AddToRole(user.Id, roleName);
        DbContext.SaveChanges();
    }

我尝试将用户添加到如上所示的角色。但是它不起作用,因为在尝试执行以下控制器操作时:

 [AuthorizeUser(Roles = RoleEnums.UserWithProfile)]
 public ActionResult Index(Guid? userProfileId)
 {

 }

授权失败。奇怪的是,它成功地授权了数据库种子中添加的用户。

private void SeedUserRoles(List<ApplicationUser> applicationUsers, DbContext dbContext)
        {
            var userStore = new UserStore<ApplicationUser>(dbContext);
            var userManager = new UserManager<ApplicationUser>(userStore);
            userManager.AddToRole(applicationUsers[0].Id, RoleEnums.UserWithProfile);
            userManager.AddToRole(applicationUsers[1].Id, RoleEnums.UserWithProfile);
            userManager.AddToRole(applicationUsers[2].Id, RoleEnums.UserWithProfile);
            userManager.AddToRole(applicationUsers[3].Id, RoleEnums.User);
        }

    private void CreateRoles(DbContext context)
    {
        var roleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));

        if (!roleManager.RoleExists(RoleEnums.Admin))
        {
            var role = new IdentityRole { Name = RoleEnums.Admin };
            roleManager.Create(role);
        }

        if (!roleManager.RoleExists(RoleEnums.User))
        {
            var role = new IdentityRole { Name = RoleEnums.User };
            roleManager.Create(role);
        }

        if (!roleManager.RoleExists(RoleEnums.UserWithProfile))
        {
            var role = new IdentityRole { Name = RoleEnums.UserWithProfile };
            roleManager.Create(role);
        }
    }

我在这里缺少什么? AddUserToRole() 方法是否不正确,为什么只有播种才能给我正确的行为?

编辑:ASP.NET Identity check user roles is not working 找到了这个,这似乎是这里的问题。但我不希望用户必须手动注销并再次登录。他们提到了一些关于更新安全标记的事情,但这对我不起作用。

Edit2:查看我发布的答案以了解我最终得到的解决方案。

【问题讨论】:

  • 如果您收到授权错误,您确定使用正确的用户添加角色吗?它应该是角色 = RoleEnums.UserWithProfile.. 的用户。数据库播种有效,因为它没有授权限制,而操作方法有身份验证限制(请参阅过滤器)
  • 令我印象深刻的是,在 AddUserToRole() 方法中,您使用字符串作为参数,而播种方法使用 RoleEnums 类的静态属性。您在调用 AddUserToRole() 时用作角色的字符串是否可能与 RoleEnums.UserWithProfile 不匹配?

标签: c# asp.net entity-framework asp.net-identity


【解决方案1】:

AddToRole 返回一个 IdentityResult。您需要检查此返回值是否存在错误字符串集合中的错误。

https://msdn.microsoft.com/en-us/library/dn497483(v=vs.108).aspx

您还应该检查您实际获得用户的 FindById 的返回。

【讨论】:

  • 我发现了这个link,看来您需要注销并登录才能更新角色。我尝试了更新 securitystamp 提示,但没有任何建议?
【解决方案2】:

MVC 5 AddToRole requires logout before it works?

我最终使用了这个问题的解决方案,因为它是我能找到的最简单的解决方案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-11
    • 1970-01-01
    • 2020-01-24
    • 2014-08-08
    • 1970-01-01
    • 2018-09-25
    • 1970-01-01
    相关资源
    最近更新 更多