简体   繁体   中英

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?

It's still pretty new and there is not much to find about it.

Controller.User.Identity is a 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. 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.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). ClaimsPrincipal.Identity is the principal identity of those identities. 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.

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 . 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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