8

In our .NET Core Web API, we have configured claim based authorization and it works perfectly. We have created role-claims and assign roles to users. We do not use user-claims.

Now I have a requirement to get users having a specific claim. In UserManager there is a method GetUsersByClaimAsync(Claim), which seems only considering user-claims. Not role claims. So in my case, it is not usable.

So I was thinking of getting roles by claim and then get the users by roles (not very efficient as it has to make several DB calls to get the users of each role separately). But even to do that, there is no straight forward method to get roles by claims in UserManager or RoleManager.

So to me, it seems there is no clean way of achieving this other than custom querying.

I'm not sure I'm missing something here. Has anyone achieved this, using a better way?

Thanks

Dan Roche
  • 5
  • 2
Wijitha
  • 1,189
  • 2
  • 12
  • 22
  • You need some navigation properties among the identity entities. For role-based authorization, I think you should forget asp.net Identity and implement custom entities. – Hadi Samadzad Jan 03 '20 at 11:27
  • I got same scenario, trying to fix that with custom Identity Server 4 repo's. – EHU Jan 03 '20 at 14:11

1 Answers1

2

Now I have a requirement to get users having a specific claim. In UserManager there is a method GetUsersByClaimAsync(Claim), which seems only considering user-claims. Not role claims. So in my case, it is not usable.

I think you could try the UserManager<TUser>.GetUsersInRoleAsync(roleName) api:

var users = await _userManager.GetUsersInRoleAsync("Role1");

By the way, to use the above api, you need enable the Role related services by :

AddDefaultIdentity<IdentityUser>(options => { /*...*/ })
    .AddRoles<IdentityRole>()
    .AddEntityFrameworkStores<AppIdentityDbContext>();
itminus
  • 23,772
  • 2
  • 53
  • 88
  • Thanks for the answer. Yeah, this was the fallback option. To use this, first, need to get all the roles having a specific claim (There could be few) and call GetUsersInRole multiple times. There is no method even to get the roles having a claim. So need to manually add some navigation props and do it. – Wijitha Jan 06 '20 at 04:07