Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.Net Core Identity Framework Get Users By Claim

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

like image 885
Wijitha Avatar asked Jan 03 '20 11:01

Wijitha


Video Answer


1 Answers

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>();
like image 92
itminus Avatar answered Oct 17 '22 22:10

itminus