以递归方式获取.NET Azure Active Directory组中的所有用户

时间:2016-10-27 14:28:24

标签: .net azure active-directory

我正在努力以递归方式获取.NET Azure Active Directory组中的所有用户。我搜索了一下,但所有文章都是Azure Active Directory组的用户成员。

任何帮助都将受到高度赞赏。

由于

Anil Jain

1 个答案:

答案 0 :(得分:2)

根据我的理解,要递归地从组中检索成员,我们只需要检测成员的类型。如果该成员是小组,我们可以再次请求成员。

我还使用Azure AD图形客户端编写了一个演示文稿供您参考:

public void testPrintMembersRecursively()
{
    var client = GraphHelper.CreateGraphClient();
    var group = (Group)client.Groups.ExecuteAsync().Result.CurrentPage.First(g => g.DisplayName == "group4");
    var groupFetcher = client.Groups.GetByObjectId(group.ObjectId);

   PrintMembersRecursively(groupFetcher, 0);
}

public void PrintMembersRecursively(Microsoft.Azure.ActiveDirectory.GraphClient.IGroupFetcher groupFetcher, int level)
{
    var membersResoult = groupFetcher.Members.ExecuteAsync().Result;
    Print(level, membersResoult);

    while (membersResoult.MorePagesAvailable)
    {
        membersResoult=membersResoult.GetNextPageAsync().Result;
        Print(level,membersResoult);
    }
}

private void Print(int level, IPagedCollection<IDirectoryObject> membersResoult)
{
    var members = membersResoult.CurrentPage;

    foreach (var obj in members)
    {
        var user = obj as Microsoft.Azure.ActiveDirectory.GraphClient.User;
        if (user != null)
            Console.WriteLine(String.Format("{0," + level * 8 + "}", user.DisplayName));
        else
        {
            var groupMember = obj as Microsoft.Azure.ActiveDirectory.GraphClient.Group;
            if (groupMember != null)
            {
                Console.WriteLine(String.Format("{0," + level * 8 + "}", groupMember.DisplayName));
                    PrintMembersRecursively(GetGroupById(groupMember.ObjectId), level + 1);
            }
        }
    }
}


public static ActiveDirectoryClient CreateGraphClient()
{
    string accessToken = "";
    string tenantId = "xxx.onmicrosoft.com"; 
    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;
}