Search code examples
asp.net-mvcasp.net-identityasp.net-identity-2

How to find all ApplicationRoles of a user in asp.net identity 2.0


I tried following code to get all the roles object (i.e. ApplicationRole not the IdentityUserRole) of a user.

string userId = User.Identity.GetUserId();

var RoleManager = this.HttpContext.GetOwinContext().Get<ApplicationRoleManager>();
var UserManager = this.HttpContext.GetOwinContext().Get<ApplicationUserManager>();

// var u = RoleManager.FindByName("").Users;
// var r = UserManager.FindById(userId).Roles;

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

var userRoles = (from roles in RoleManager.Roles
                    where roleNames.Contains(roles.Name)
                    select roles
                    ).ToList();

But it not seem consistent and trivial and it works Only with the current user. I hope there would be some better way of doing this.

Edit 1:

My RoleManager is the class derived from IdentityRole have some extra properties e.g. Description.

public class ApplicationRole : IdentityRole
{
    public ApplicationRole() : base() { }
    public ApplicationRole(string name, string description)
        : base(name)
    {
        this.Description = description;
    }
    public virtual string Description { get; set; }
}

Note: IdentityUserRole / user.Roles / role.Users are not the Roles. All three represent the joining table between User & Role


Solution

  • var selectedRoleNames = from uf in user.UserRoles
                            join r in RoleManager.Roles on uf.RoleID equals r.ID
                            select r;
    

    This gets roles for the given user. If the given user is not the current user, then don't use User.Identity, but get the user via UserManager.

    Or, if you already have any user id then...

    var selectedRoleNames = from r in RoleManager.Roles
                            where r.Users.Select(u => u.UserId).Contains(user.Id)
                            select r;