.Net Core身份框架按声明获取用户

huangapple go评论96阅读模式
英文:

.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&lt;IdentityUser&gt;(options => { /.../ })
<b>.AddRoles&lt;IdentityRole&gt;()</b>
.AddEntityFrameworkStores&lt;AppIdentityDbContext&gt;();
</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&lt;TUser&gt;.GetUsersInRoleAsync(roleName) api:

var users = await _userManager.GetUsersInRoleAsync(&quot;Role1&quot;);

By the way, to use the above api, you need enable the Role related services by :
<pre>
AddDefaultIdentity&lt;IdentityUser&gt;(options => { /.../ })
<b>.AddRoles&lt;IdentityRole&gt;()</b>
.AddEntityFrameworkStores&lt;AppIdentityDbContext&gt;();
</pre>

huangapple
  • 本文由 发表于 2020年1月3日 19:16:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/59577633.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定