简体   繁体   中英

.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

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 => { /*...*/ })
    
    .AddEntityFrameworkStores<AppIdentityDbContext>();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM