Returning users in groups from Azure AD using MS Graph

We store our user and group accounts in Azure AD, and I needed to retrieve the members of a group in order to email them. We use Microsoft Graph to do such things as these. The “User” class referenced below is the Microsoft.Graph.Models.User class.

You first will need the ID of the group. To do this, run the query below in Graph Explorer. You will also need to add a request header with a key of ConsistencyLevel with a value of eventual. (The “Request headers” section is just below where you type in the query of Graph Explorer):

https://graph.microsoft.com/v1.0/groups?$search="displayName:Coaster Users"&$count=true

With the ID that is returned, plug it into your query (the commandString variable below). You’ll probably want to put it in appSettings.json or a client secret. I have defined a class called GraphService where the ReturnUsersInADGroup is defined:

public async Task<List<User>> ReturnUsersInADGroup()
{
        var token = await _tokenAcquisition.GetAccessTokenForUserAsync(new string[] { "User.Read", "Directory.Read.All" });
        _httpClient.DefaultRequestHeaders.Authorization = new System.Net.Http.Headers.AuthenticationHeaderValue("Bearer", token);

        List<User> usersInGroup = new List<User>();
        string commandString = "https://graph.microsoft.com/v1.0/groups/aaaaaaaa-d277-3e5e-39e7-fffff4349437?$expand=members";

        var usersRequest = await _httpClient.GetAsync(commandString);
        var usersRaw = System.Text.Json.JsonDocument.Parse(await usersRequest.Content.ReadAsStreamAsync());
        var usersValue = usersRaw.RootElement.GetProperty("members");
        User[] users = JsonConvert.DeserializeObject<User[]>(usersValue.GetRawText());
        usersInGroup.AddRange(users);

        return usersInGroup;
}

Finally, define a method that pulls the values. I’m working with a Blazor app, so I have defined the service in the Program.cs file and use dependency injection:

builder.Services.AddScoped<GraphService>();

And in the Razor file:

@inject GraphService graphService

private void GetEmailAddresses() 
{
    var users = await graphService.ReturnUsersInADGroup();
    List<string> emailAddresses = new List<string>();
    emailAddresses = users.Select(u => u.Mail).ToList();
}

  1. Leave a comment

Leave a comment