Home > Enterprise >  Querying Azure AD using Graph API
Querying Azure AD using Graph API

Time:09-15

I'm trying to retrieve all users for a given AD domain. Whilst I have managed to retrieve the user list successfully, the next step is to identify which groups the user is a member of. This is where it gets hard.

Step 1)

 var clientSecretCredential = new ClientSecretCredential(configuration.TenantId, configuration.ClientId, ClientSecret);

 GraphServiceClient graphClient = new GraphServiceClient(clientSecretCredential);
 return await Task.FromResult(graphClient);

This gets me a successful connection to the GraphClient

 var users = await graphClient.Users.Request().GetAsync();

 foreach (var user in users)
 {
     Console.WriteLine(user.DisplayName);
 }

displays the list of users (using their DisplayName)

Step 2)

var groups = await graphClient.Users[user.Id].TransitiveMemberOf.Request().GetAsync();

This gets me the user's groups. Finally I would like to display the actual group's name....and this is where it fails. I am able to iterate over around groups but the only available properties are things like 'id' there is no DisplayName property.

Any help here would be appreciated.

CodePudding user response:

Could you please try to run the sample code :

var page = await graphClient
    .Users[userObjectId]
    .MemberOf
    .Request()
    .GetAsync();

var names = new List<string>();
names.AddRange(page
        .OfType<Group>()
        .Select(x => x.DisplayName)
        .Where(name => !string.IsNullOrEmpty(name)));
while (page.NextPageRequest != null)
{
    page = await page.NextPageRequest.GetAsync();
    names.AddRange(page
        .OfType<Group>()
        .Select(x => x.DisplayName)
        .Where(name => !string.IsNullOrEmpty(name)));
}

return names;

Sample question - How to get group names of the user is a member of using Microsoft Graph API?

Hope this helps. Thanks

  • Related