简体   繁体   中英

MVC5 how to iterate through an azure active directory user group

I've managed to get the group I want from AAD by using

ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(serviceRoot,
              async () => await GetTokenForApplication());

        // use the token for querying the graph to get the user details

        var result = await activeDirectoryClient.Groups.Where(u => u.DisplayName.Equals("myGroupName")).ExecuteAsync();

But I'm not sure how to iterate through the group I got and add all the users from that group into a list.

Do this:

List<IGroup> groups = result.CurrentPage.ToList();
foreach (IGroup group in groups)
{
    // do whatever you need to
}

EDIT

does IGroup have and property that allows me to get the users in that group such as members

Yes it does but you will need to explicitly ask for it to be expanded. Here is how to get all the users for the group:

var groups = await activeDirectoryClient.Groups
    .Where(g => g.DisplayName == groupName).Expand(g => g.Members)
    .ExecuteAsync();

var usersForGroup = new List<User>();
foreach(IGroup thisGroup in groups)
{
    do
    {
        var thisGroupUsers = 
            thisGroup.Members.CurrentPage.Select(m => m as User)).Where(u => u != null);
        allUsers.AddRange(thisGroupUsers);

        // get next page asynchronously
        await thisGroup.Members.GetNextPageAsync();
    } while(thisGroup.Members.MorePagesAvailable)

}

When you have the group's object ID, you can get the direct members using this URL in the graph API:

https://graph.windows.net/myorganization/groups/{object_id}/$links/members?api-version

The IGroup result you get in your code (eg using result.First() ), does contain a Members property, which you can use to loop through the members.

You can use an IGroupFetcher to retrieve group members:

var group = await adClient.Groups.Where(g => g.ObjectId == groupObjectId).ExecuteSingleAsync();
IGroupFetcher groupfetcher = (Group)group;
var membersResult = await groupfetcher.Members.ExecuteAsync();

var more = true;
while (more)
{
    foreach (var member in membersResult.CurrentPage) 
    {
    //... remember to handle that members can be other groups
    }
    if (!membersResult.MorePagesAvailable)
    {
        more = false;
    }
    else
    {
        // get next page in results
        membersResult = await membersResult.GetNextPageAsync();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM