[ACCEPTED]-Get list of users with assigned roles in asp.net identity 2.0-asp.net-identity-2

Accepted answer
Score: 40

Not an expert, but ...

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

So I ended up doing something 1 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
Score: 13

I find the role by the role name input. After, I 1 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;
}
Score: 7

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

roleManager.FindByName("Administrator").Users

or

roleManager.FindByName("CanEdit").Users

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

Score: 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 2 be interested to hear if this was better 1 or worse than the other solutions here.

Score: 4

There are three ways you can do it.

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

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

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

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

Do not forget 4 to add namespace,

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

For some reasons like integration 3 testing etc, you may directly want to use 2 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 1 helps.

Thanks /dj @debug_mode

Score: 0

Remove the .Email and add UserName or whatever was added 1 to the ASPNetUsers for name.

private void AddAddminToMail(MailMessage message)
{
    var roles = db.Roles.Include(m => m.Users).Where(m => m.Name == "Admin").First();
    foreach (var user in roles.Users)
        {
            var id = user.UserId;
            var userEmail = db.Users.Find(id).Email;
            message.To.Add(userEmail);
        }      
}
Score: 0

the code working for me was as following:

  var users = roleManager.FindByName(roleName).Users.Select(x => x.UserId);
  var usersInRole = Users.Where(u => users.Contains(u.Id));

0

Score: 0

Since bits like this tend to impact performance, I 5 tried the other answers posted here and 4 looked at the SQL they generated. This seems 3 to be the most performant way of getting 2 all the user's email addresses currently.

public void SendEmailToUsersInRole(string roleName)
{
    MailMessage message = new MailMessage();
    ...

    using (var usersDB = new ApplicationDbContext())
    {
        var roleId = 
            usersDB.Roles.First(x => x.Name == roleName).Id;

        IQueryable<string> emailQuery =
            usersDB.Users.Where(x => x.Roles.Any(y => y.RoleId == roleId))
                         .Select(x => x.Email);

        foreach (string email in emailQuery)
        {
            message.Bcc.Add(new MailAddress(email));
        }
    }

    ...
}

The 1 SQL that it executes is shown below:

SELECT TOP (1) 
    [Extent1].[Id] AS [Id], 
    [Extent1].[Name] AS [Name]
    FROM [dbo].[AspNetRoles] AS [Extent1]
    WHERE N'Reviewer' = [Extent1].[Name]

SELECT 
    [Extent1].[Email] AS [Email]
    FROM [dbo].[AspNetUsers] AS [Extent1]
    WHERE  EXISTS (SELECT 
        1 AS [C1]
        FROM [dbo].[AspNetUserRoles] AS [Extent2]
        WHERE ([Extent1].[Id] = [Extent2].[UserId]) AND ([Extent2].[RoleId] = @p__linq__0)
    )


-- p__linq__0: '3' (Type = String, Size = 4000)

More Related questions