Net 标识获取登录用户的所有角色

我按照 这个教程创建了一个基于角色的菜单。在页面的某个地方,你会看到这行代码:

String[] roles = Roles.GetRolesForUser();

它返回当前登录用户的所有角色。我想知道如何使用新的 ASP.NET 标识系统来实现这一点?

它仍然是相当新的,没有太多的发现。

100209 次浏览

Controller.User.IdentityClaimsIdentity。您可以通过检查索赔来获得角色列表..。

var roles = ((ClaimsIdentity)User.Identity).Claims
.Where(c => c.Type == ClaimTypes.Role)
.Select(c => c.Value);

- 更新

再分解一点。

using System.Security.Claims;


// ........


var userIdentity = (ClaimsIdentity)User.Identity;
var claims = userIdentity.Claims;
var roleClaimType = userIdentity.RoleClaimType;
var roles = claims.Where(c => c.Type == ClaimTypes.Role).ToList();


// or...
var roles = claims.Where(c => c.Type == roleClaimType).ToList();

下面是上述解决方案的扩展方法。

    public static List<string> Roles(this ClaimsIdentity identity)
{
return identity.Claims
.Where(c => c.Type == ClaimTypes.Role)
.Select(c => c.Value)
.ToList();
}

不要使用@using System.IdentityModel.Declaration 命名空间,而是使用

@ using System

    @using System.Security.Claims
@using Microsoft.AspNet.Identity
@{
var claimsIdentity = User.Identity as System.Security.Claims.ClaimsIdentity;
var customUserClaim = claimsIdentity != null ? claimsIdentity.Claims.FirstOrDefault(x => x.Type == "cutomType") : null;
var customTypeValue= customUserClaim != null ? customUserClaim .Value : User.Identity.GetUserName();
var roleOfUser = claimsIdentity != null ? claimsIdentity.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Role).Value :"User";


}

SignInManager获取 Identity User 之后,在 UserManager上调用 GetRolesAsync,并将标识用户作为参数传递。

它将返回标识用户已注册的角色列表。

var rolesList = await userManager.GetRolesAsync(identityuser).ConfigureAwait(false);

我不认为任何一个答案是完全正确的,因为它们都采用了登录用户的主要身份。UserClaimsPrincipal,可以有多个标识(ClaimsPrincipal.Identities属性)。ClaimsPrincipal.Identity是这些身份的 主要身份主要身份。因此,要获取用户的所有角色,您需要从所有标识中获取角色。这就是内置的 ClaimPrincipal.IsInRole(string roleName)方法所做的,即它检查给定的 roleName是否存在于任何标识中。

所以获得所有角色的正确方法是这样的:

    public static class ClaimsPrincipalExtensions


public static IEnumerable<string> GetRoles(this ClaimsPrincipal principal)
{
return principal.Identities.SelectMany(i =>
{
return i.Claims
.Where(c => c.Type == i.RoleClaimType)
.Select(c => c.Value)
.ToList();
});
}
}

用作

var roles = User.GetRoles()

另外,请注意在标识 Identity.RoleClaimType中设置的索赔类型的使用,而不是静态索赔类型 ClaimTypes.Role 。这是必需的,因为角色声明类型可以被每个标识覆盖,例如,当通过 JWT 令牌接收标识时,该令牌提供了使用自定义声明名称作为角色声明类型的能力。

试试以下方法:

var roles = user.Claims.Where(c => c.Type == ClaimTypes.Role).Select(x => x.Value).FirstOrDefault();