When using the latest (2.1.0) version of the Azure AD Graph Client Library, it is not trivial to figure out how to get a group’s members. Even with the code samples there is still some trickery needed. This post shows you how. It assumes you’ve got the authentication part figured out already, of course.
List results = new List();
ActiveDirectoryClient adClient = CreateClient(userId);
IUser user = await adClient.Users.Where(x => x.Mail == model.Email).ExecuteSingleAsync();
if (user != null)
{
var pagedCollection = await ((IUserFetcher)user).MemberOf.ExecuteAsync();
do
{
results.AddRange(pagedCollection.CurrentPage.OfType().Select(role => role.DisplayName));
pagedCollection = await pagedCollection.GetNextPageAsync();
}
while (pagedCollection != null);
}
return results;
A few comments are in place.
- The creation of the ActiveDirectoryClient on line 2 is ‘hidden’ in the helper method `CreateClient()`. Not relevant here.
- We retrieve a matching user by doing comparison on the `Email` field. Change this to anything you like.
- We use the very convenient `ExecuteSingleAsync()` since we know we only want one, and don’t care about paging results.
- IMPORTANT we cast the user (on line 6) to an `IUserFetcher`, this enables us to retrieve (paged) results of all group members.
- On line 9 we use a simple LINQ filter (`OfType()`) to get only users. Group members can be of type groups and principals too, but we don’t care about them.
If you need other samples, take a look at this page on Github, it contains a lot of relevant sample code.