简体   繁体   English

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

[英]asp.net identity get all roles of logged in user

I created a role based menu for which I followed this tutorial.我创建了一个基于角色的菜单,并遵循了本教程。 Some where down that page you'll see this line of code:在该页面的某些位置,您会看到这行代码:

String[] roles = Roles.GetRolesForUser();

It returns all roles of the currently logged in user.它返回当前登录用户的所有角色。 I was wondering how to accomplish this with the new ASP.NET Identity system?我想知道如何使用新的 ASP.NET 身份系统来实现这一点?

It's still pretty new and there is not much to find about it.它仍然很新,没有太多可找到的东西。

Controller.User.Identity is a ClaimsIdentity . Controller.User.Identity是一个ClaimsIdentity You can get a list of roles by inspecting the claims...您可以通过检查声明来获取角色列表...

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

--- update --- - - 更新 - -

Breaking it down a bit more...再分解一点...

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

Here's an extension method of the above solution.这是上述解决方案的扩展方法。

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

After getting Identity User from SignIn Manager, callGetRolesAsync on UserManager and pass identity user as parameter.从登录管理器获取身份用户后,在 UserManager 上调用 GetRolesAsync 并将身份用户作为参数传递。 It will return of List of roles, identity user enrolled in它将返回角色列表,身份用户注册

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

Don't use @using System.IdentityModel.Claims namespace, Instead of that use不要使用@using System.IdentityModel.Claims 命名空间,而不是使用

@using System.Security.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";

}

I don't think any of the answers is entirely correct as they all take the principal identity of the logged in user.我不认为任何答案是完全正确的,因为它们都采用登录用户的主要身份。 User is a ClaimsPrincipal and can have multiple identities ( ClaimsPrincipal.Identities property). UserClaimsPrincipal并且可以有多个身份( ClaimsPrincipal.Identities属性)。 ClaimsPrincipal.Identity is the principal identity of those identities. ClaimsPrincipal.Identity是这些身份的主要身份 So to get all roles of the user you need to get roles from all identities.因此,要获取用户的所有角色,您需要从所有身份中获取角色。 This is what the built-in ClaimPrincipal.IsInRole(string roleName) method does ie it checks the given roleName exists in any of the identities.这就是内置的ClaimPrincipal.IsInRole(string roleName)方法所做的,即它检查给定的roleName存在于任何身份中。

So the correct way to get all roles is something like this:所以获得所有角色的正确方法是这样的:

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

and used as并用作

var roles = User.GetRoles()

Also, note the use of claim type set in the identity Identity.RoleClaimType instead of the static claim type ClaimTypes.Role .另外,请注意使用身份Identity.RoleClaimType设置的声明类型,而不是静态声明类型ClaimTypes.Role This is needed because the role claim type can be overridden per identity eg when identity is received via a JWT token which provides ability to use a custom claim name as the role claim type.这是必需的,因为可以覆盖每个身份的角色声明类型,例如当通过 JWT 令牌接收身份时,该令牌提供使用自定义声明名称作为角色声明类型的能力。

try below:试试下面:

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

You can also use such syntax:您也可以使用这样的语法:

var userClaims = User.Identity as System.Security.Claims.ClaimsIdentity;
var roles = userClaims.FindAll("http://schemas.microsoft.com/ws/2008/06/identity/claims/role").ToList();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM