通过Microsoft Graph从Azure AD获取组中的用户 [英] Get Users in Group from Azure AD via Microsoft Graph
问题描述
我正在通过Microsoft Graph从AzureAD请求用户列表.
I'm requesting a list of users from AzureAD via Microsoft Graph.
我找回了User对象,但是它们的MemberOf属性始终为null.
I get the User objects back, but their MemberOf property is always null.
我以为我可以使用Expand专门请求该属性,尽管它不会引起任何错误,但也不会填充该属性.
I thought I could use Expand to request that property specifically, and while it causes no error it also doesn't populate the property.
此来自中旬的问题和答案2016 建议该功能当时处于测试阶段,我想它现在已经可以升级到生产API了?
This question and answer from mid-2016 suggests this functionality was in beta at that time, and I thought it would have graduated to the production API by now?
var allUsers = await graphClient
.Users
.Request()
.Expand("memberOf")
.GetAsync();
var usersInGroup = allUsers
.Where(user => user.MemberOf.Any(memberOf => memberOf.Id.Equals(groupId, StringComparison.OrdinalIgnoreCase)))
.ToList();
(我尝试扩展"memberOf"和"MemberOf".)
(I've tried expanding "memberOf" and "MemberOf".)
我可以通过网上论坛检索成员列表.
I can retrieve a list of members via the Group.
但是那会返回一个ID列表,所以我不得不发出两个请求,而不仅仅是一个.
But that returns a list of IDs, so I'd have to make two requests instead of just the one.
var groupMembers = await graphClient
.Groups[groupId]
.Members
.Request()
.GetAsync();
var groupMemberIds = groupMembers
.Select(groupMember => groupMember.Id)
.ToList();
var allUsers = await graphClient
.Users
.Request()
.GetAsync();
var usersInGroup = allUsers
.Where(user => groupMemberIds.Contains(user.Id))
.ToList();
如果获取属于该组的ID,然后过滤用户是正确的方法,那很好,我会继续处理.
If getting the IDs belonging to the Group, and then filtering the Users is the correct way then that's fine, I'll go with that.
理想情况下,我想提出一个请求来检索User对象并在服务器端完成过滤.
Ideally I'd like to make a single request to retrieve the User objects and have the filtering done server side.
例如
var usersInGroup = await graphClient
.Users
.Request()
.Filter($"memberOf eq {groupId}")
.GetAsync();
很明显,该过滤器将不起作用,但类似的选择将是理想的选择.
Obviously that filter won't work, but something like that would be ideal.
(有人指出,我一直在链接到错误的文档集,所以我删除了那些链接,以免引起将来读者的困惑)
推荐答案
Getting the membership for a single Group can be done using $expand
. For example, running the following query in Graph Explorer will return the Group HRTaskforce
and all of it's members:
https://graph.microsoft.com/v1.0/groups/02bd9fd6-8f93-4758-87c3-1fb73740a315?$expand=members
使用.NET Client SDK,您可以执行以下操作:
Using the .NET Client SDK, you could do something like this:
var groupAndMembers = await _tokenService.Token.GetGraphServiceClient()
.Groups["02bd9fd6-8f93-4758-87c3-1fb73740a315"]
.Request()
.Expand("members")
.GetAsync();
var usersInGroup = groupAndMembers.Members.ToList();
此外,链接到的所有文档都来自Azure AD Graph API.请注意,这是一个不同的API,并不总是安全地假设Azure AD Graph中的资源和方法与Microsoft Graph一样可用(或以相同的方式工作)
这篇关于通过Microsoft Graph从Azure AD获取组中的用户的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!