Azure Graph API 列出子组中的用户

Azure Graph API list users in child groups

我有一个名为 "Building Residents" 的群组。在该组中,我为每个公寓分配了 2 个组:

- Apt1a_Renters
- Apt1a_Owners

- Apt2a_Renters
- Apt2a_Owners

等等等等...

一个人可以在 Apt2a_Owners 组中,也可以在 Apt1a_Renters 组中。

我想为用户查询 "Building Residents" 组的所有成员,但是当我这样做时,我只是取回其中的组。

有什么方法可以使用单个查询列出所有建筑居民而不带回重复项(apt2a_owners 和 apt1a_renters 中的同一个人)?

Azure Graph REST 只能从一个组中获取直接成员。递归获取成员用户,需要我们自己实现。以下是使用 Azure AD Graph 库与 C# 连接的代码示例,供您参考:

public void testGetMembersRecursively()
{
    var accessToken="";
    var tenantId="";
    var groupName="";
    var client = GraphHelper.CreateGraphClient(accessToken,tenantId);
    var group = (Group)client.Groups.ExecuteAsync().Result.CurrentPage.First(g => g.DisplayName ==groupName);
    var groupFetcher = client.Groups.GetByObjectId(group.ObjectId);
    List<string> users = new List<string>();
    GetMembersRecursively(groupFetcher, users);
    Console.WriteLine(String.Join("\n", users.Distinct<string>().ToArray()));
}

public void GetMembersRecursively(Microsoft.Azure.ActiveDirectory.GraphClient.IGroupFetcher groupFetcher, List<string> users)
{
    var membersResoult = groupFetcher.Members.ExecuteAsync().Result;
    AddMember( membersResoult, users);

    while (membersResoult.MorePagesAvailable)
    {
        membersResoult = membersResoult.GetNextPageAsync().Result;
        AddMember(membersResoult, users);
    }
}

public void AddMember( IPagedCollection<IDirectoryObject> membersResoult, List<string> users)
{
    var members = membersResoult.CurrentPage;

    foreach (var obj in members)
    {
        var _user = obj as Microsoft.Azure.ActiveDirectory.GraphClient.User;
        if (_user != null)
            users.Add(_user.DisplayName);
        else
        {
            var groupMember = obj as Microsoft.Azure.ActiveDirectory.GraphClient.Group;
            if (groupMember != null)
            {
                GetMembersRecursively(GetGroupById(groupMember.ObjectId), users);
            }
        }
    }
}

GraphHelper class:

class GraphHelper
{
    public static ActiveDirectoryClient CreateGraphClient(string accessToken, string tenantId)
    {
        string graphResourceId = "https://graph.windows.net";

        Uri servicePointUri = new Uri(graphResourceId);
        Uri serviceRoot = new Uri(servicePointUri, tenantId);

        ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot, async () => await Task.FromResult(accessToken));

        return activeDirectoryClient;
    }    
}