英文:
.Net Core Identity Framework Get Users By Claim
问题
在我们的.NET Core Web API中,我们已经配置了基于声明的授权,它运行得很完美。我们创建了角色声明并分配角色给用户。我们不使用用户声明。
现在我有一个要求,需要获取具有特定声明的用户。在UserManager中有一个方法GetUsersByClaimAsync(Claim),它似乎只考虑用户声明,而不是角色声明。所以在我的情况下,它不可用。
所以我在考虑通过声明获取角色,然后通过角色获取用户(这不是非常高效,因为它必须分别获取每个角色的用户,需要进行多次数据库调用)。但即使这样做,UserManager或RoleManager中也没有直接的方法来根据声明获取角色。
所以对我来说,似乎没有其他比自定义查询更干净的方法来实现这一点。
我不确定我是否漏掉了什么。有人是否通过更好的方式实现了这一点?
谢谢。
英文:
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
答案1
得分: 2
> 现在我有一个要求,需要获取具有特定声明的用户。在UserManager中有一个名为GetUsersByClaimAsync(Claim)的方法,它似乎只考虑用户声明,而不考虑角色声明。所以在我的情况下,它无法使用。
我认为你可以尝试使用 UserManager<TUser>.GetUsersInRoleAsync(roleName)
API:
var users = await _userManager.GetUsersInRoleAsync("Role1");
顺便说一下,要使用上述API,你需要通过以下方式启用与Role
相关的服务:
<pre>
AddDefaultIdentity<IdentityUser>(options => { /.../ })
<b>.AddRoles<IdentityRole>()</b>
.AddEntityFrameworkStores<AppIdentityDbContext>();
</pre>
英文:
> 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 :
<pre>
AddDefaultIdentity<IdentityUser>(options => { /.../ })
<b>.AddRoles<IdentityRole>()</b>
.AddEntityFrameworkStores<AppIdentityDbContext>();
</pre>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论