asp.net identity获取登录用户的所有角色

时间:2014-02-10 22:07:35

标签: c# asp.net-mvc roles

我创建了一个基于角色的菜单,我跟着this教程。在该页面的某些位置,您将看到以下代码行:

String[] roles = Roles.GetRolesForUser();

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

它仍然很新,而且找不到它。

5 个答案:

答案 0 :(得分:99)

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();

答案 1 :(得分:16)

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

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

答案 2 :(得分:2)

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

  

@using System.Security.Claims

    @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";

}

答案 3 :(得分:0)

从SignIn Manager获取身份用户后,请在UserManager上调用GetRolesAsync并将身份用户作为参数传递。 它将返回角色列表,已注册

的身份用户
var rolesList = await userManager.GetRolesAsync(identityuser).ConfigureAwait(false);

答案 4 :(得分:-1)

我认为任何答案都不完全正确,因为它们都采用了登录用户的主要身份。 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令牌接收到身份时,该令牌提供了使用自定义声明名称作为角色声明类型的功能。