Azure Graph API列出子组中的用户

时间:2017-01-17 14:09:38

标签: azure azure-ad-b2c azure-active-directory azure-ad-graph-api

我有一个名为“建筑居民”的小组。在那个小组中,每个公寓都有两组:

- Apt1a_Renters
- Apt1a_Owners

- Apt2a_Renters
- Apt2a_Owners

等等...

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

我想查询“建筑居民”组的所有成员,但是当我这样做时,我只是回到其中的组。

使用单个查询是否有任何方法可以列出所有建筑物居民而不会带来重复(apt2a_owners和apt1a_renters中的同一个人)?

1 个答案:

答案 0 :(得分:2)

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 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;
    }    
}