asp.net identity get all roles of logged in user

前端 未结 5 2179
遇见更好的自我
遇见更好的自我 2020-11-28 04:49

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


        
5条回答
  •  Happy的楠姐
    2020-11-28 05:23

    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 i.e. 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 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 e.g. when identity is received via a JWT token which provides ability to use a custom claim name as the role claim type.

提交回复
热议问题