Get list of users with assigned roles in asp.net identity 2.0

54,095

Solution 1

Not an expert, but ...

There seemed to be no built in funcionality for this in Identity and I could not get it work from built in Roles also (it seems to not work with claims based Identity).

So I ended up doing something like this:

var users = context.Users        
    .Where(x => x.Roles.Select(y => y.Id).Contains(roleId))
    .ToList();
  • x.Roles.Select(y => y.Id) gets a list of all role ids for user x
  • .Contains(roleId) checks if this list of ids contains necessary roleId

Solution 2

I find the role by the role name input. After, I find list users by id of the role.

public List<ApplicationUser> GetUsersInRole(string roleName)
{
 var roleManager = 
  new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new  ApplicationDbContext()));
 var role = roleManager.FindByName(roleName).Users.First();
 var usersInRole = 
  Users.Where(u => u.Roles.Select(r => r.RoleId).Contains(role.RoleId)).ToList();
 return usersInRole;
}

Solution 3

If you want to avoid using the context directly you can use the RoleManager with the following snippet

roleManager.FindByName("Administrator").Users

or

roleManager.FindByName("CanEdit").Users

For a short discussion about this topic have a look at the this thread

Solution 4

Using the RoleManager gives you this solution:

if(roleManager.RoleExists("CanEdit"))
{
    var idsWithPermission = roleManager.FindByName("CanEdit").Users.Select(iur => iur.Id);
    var users = db.Users.Where(u => idsWithPermission.Contains(u.Id));
}

I'd be interested to hear if this was better or worse than the other solutions here.

Solution 5

There are three ways you can do it.

In the Controller current logged in user's role can be checked as follows,

  if(User.IsInRole("SysAdmin"))
        {

Outside Controller you can check whether a particular user belongs to a Role as follows:

 ApplicationUserManager UserManager = HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
        var roles = UserManager.GetRoles(userid);
        if (roles.Contains("SysAdmin"))
        {
        }

Do not forget to add namespace,

using Microsoft.AspNet.Identity.EntityFramework;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;

For some reasons like integration testing etc, you may directly want to use EF to find user's role as follows:

string userId = User.Identity.GetUserId();
        ApplicationDbContext db = new ApplicationDbContext();
        var role = (from r in db.Roles where r.Name.Contains("Admin") select r).FirstOrDefault();
        var users = db.Users.Where(x => x.Roles.Select(y => y.RoleId).Contains(role.Id)).ToList();
        if (users.Find(x => x.Id == userId) != null)
        {
            // User is in the Admin Role
        }

Hope it helps.

Thanks /dj @debug_mode

Share:
54,095
Abhimanyu
Author by

Abhimanyu

Hello! I'm so glad to have you here. My name is Abhimanyu Kumar Vatsa, this is my personal blog focused on Microsoft Technologies. I'm a Microsoft MVP (2012, 2013, 2014, 2015), C# Corner MVP (2010, 2011) and a published author of Instant Razor View Engine How-To book from PACKT Publication. I am good in building web scale applications using Microsoft tools and technologies including ASP.NET Web Forms, MVC, C#, JavaScript libraries (includes jQuery, AngularJS, NodeJS, Knockout, Backbone.js, Ember.js, Underscore.js, TypeScript, Bootstrap, Mustache, jQuerytmp, Handlebars etc) Azure (includes Virtual Machine Ops, Websites, SQL Databases, Media Services), database stuff includes SQL Server, MySQL, Oracle, DocumentDB (NoSQL), Hadoop etc. In addition with Microsoft Web Stack Technologies, I'm also cool in PHP, Python, Java etc but my specialty is always Microsoft. I love to work with Internet scale projects using Microsoft stuffs that has potential to change the every day use of technology.

Updated on July 03, 2020

Comments

  • Abhimanyu
    Abhimanyu almost 4 years

    I have a drop down list box which lists roles. I want to get the list of users having that role. I mean list of users that are in "Administrator" role or "CanEdit" role. Here is my code:

    public IQueryable<Microsoft.AspNet.Identity.EntityFramework.IdentityUser> 
      GetRolesToUsers([Control] string ddlRole)
    {    
      //ddlRole returns role Id, based on this Id I want to list users
    
      var _db = new ApplicationDbContext();
      IQueryable<Microsoft.AspNet.Identity.EntityFramework.IdentityUser> query = _db.Users;
    
      if (ddlRole != null)
      {
        //query = query.Where(e => e.Claims == ddlRole.Value);  ???????              
      }
    
      return query;
    }
    

    Please help.

    Updated Code (still error)

    public List<IdentityUserRole> GetRolesToUsers([Control]string ddlRole)
    {
    
      var roleManager = 
       new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(new ApplicationDbContext()));
      var users = roleManager.FindByName("Administrator").Users.ToList();
      return users;
    }
    

    Error: The Select Method must return one of "IQueryable" or "IEnumerable" or "Microsoft.AspNet.Identity.EntityFramework.IdentityUser" when ItemType is set to "Microsoft.AspNet.Identity.EntityFramework.IdentityUser".

    I tried various castings but none of them helped.

    UPDATE (working solution)

    Thanks to chris544, his idea helped me to fix this. Here is working method:-

    public List<ApplicationUser> GetRolesToUsers([Control]string ddlRole)
    {
      var context = new ApplicationDbContext();
      var users =
        context.Users.Where(x => x.Roles.Select(y => y.RoleId).Contains(ddlRole)).ToList();
    
      return users;
    }