ASP.NET核心身份角色,声明和用户 [英] ASP.NET Core Identity Role, Claim and User

查看:113
本文介绍了ASP.NET核心身份角色,声明和用户的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是ASP.NET Core的初学者.我陷入角色,声明和用户关系中.

I am an ASP.NET Core beginner. I'm stuck in role, claim and user relationship.

我有一个用户 Ben ,该用户属于 Admin 角色. 管理员角色在数据库中声明了查看页面编辑页面.

I have a user Ben, user belongs to Admin role. Admin role has claims view-page and edit-page in database.

但是我无法获得属于该用户的声明和角色:

But I can't get claims and roles to be belonging to that user:

(请参阅代码中的注释)

(Please see comment in code)

var user = await _userManager.FindByNameAsync(applicationUser.UserName);
if(user != null) {
    var userClaims = await _userManager.GetClaimsAsync(user); // empty, WHY ?
    var userRoles = await _userManager.GetRolesAsync(user); // ['admin']
    var adminRole = DbContext.Roles.FirstOrDefault(x => x.Name == "Admin");
    IList<Claim> adminClaims;
    if(adminRole != null)
    {
        adminClaims = await _roleManager.GetClaimsAsync(adminRole);
        // correct => ['view-page', 'edit-page']
    }
    }
}

在我看来,我知道用户是角色的成员时,他会继承该角色的声明.

In my mind, I understand when a user is a member of a role, he inherit that role's claims.

默认的ASP.NET Identity具有5个表:

Default ASP.NET Identity have 5 tables:

  • 用户.
  • 角色.
  • UserRoles-用户可以具有多个角色.
  • RoleClaims-角色可以有很多主张.
  • UserClaims-用户可以有很多主张.

我认为正确吗?为什么userManager.GetClaimsAsync(user)返回空声明?

Do i think correct ? Why userManager.GetClaimsAsync(user) returns empty claims ?

有什么建议吗?

推荐答案

为什么userManager.GetClaimsAsync(user)返回空声明?

Why userManager.GetClaimsAsync(user) returns empty claims ?

因为UserManager.GetClaimsAsync(user)查询UserClaims表.相同的 RoleManager.GetClaimsAsync(role)查询RoleClaims表.

Because UserManager.GetClaimsAsync(user) queries the UserClaims table. Same for RoleManager.GetClaimsAsync(role) queries the RoleClaims table.

但是,根据设计,当用户是角色成员时,ASP.NET Identity Core会自动继承角色的声明.您可以检查ClaimsPrincipal,例如在控制器操作内部:

But by design in ASP.NET Identity Core when a user is a member of a role, they automatically inherit the role's claims. You can check the ClaimsPrincipal, for example inside a controller action:

var claims = User.Claims.ToList();

您可以在

You can see the code in UserClaimsPrincipalFactory.cs that creates a ClaimsPrincipal from an user.

这篇关于ASP.NET核心身份角色,声明和用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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