Search code examples
c#azureazure-active-directorymicrosoft-graph-apiasp.net-core-webapi

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


I want to know the list of groups the user is a member of in AAD. Based on the membership of the group they can do another function. To achieve this I used the MS Graph API, but I get only group Ids, not the group names. I used the following two ways using graph API. The first method used,

await  graphClient.Users[upn].GetMemberGroups(false).Request().PostAsync()

response:

[ "fee2c45b-915a-4a64-b130-f4eb9e75525e", "4fe90ae7-065a-478b-9400-e0a0e1cbd540", "e0c3beaf-eeb4-43d8-abc5-94f037a65697" ]

The second method used,

await  graphClient.Users[upn].MemberOf.Request().GetAsync();

response:

[
    {
        "deletedDateTime": null,
        "id": "1c4934554-5006-403a-bf4f-bsdfeerwfs6fe6f",
        "oDataType": "#microsoft.graph.group",
        "additionalData": {
            "creationOptions": [],
            "isAssignableToRole": null,
            "resourceBehaviorOptions": [],
            "resourceProvisioningOptions": []
        }
    },
    {
        "deletedDateTime": null,
        "id": "f8975c2f-7651d-4f3a-1234-4ec3808a0ac2",
        "oDataType": "#microsoft.graph.group",
        "additionalData": {
            "creationOptions": [
                []
            ],
            "isAssignableToRole": null,
            "resourceBehaviorOptions": [],
            "resourceProvisioningOptions": [
                []
            ]
        }
    }
]

What I need is along with the group name and group ID. How do I get both together in an efficient way? Or are there any other method which i can try for this purpose?


Solution

  • For me the following works for getting group names:

    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;
    

    There should be a DisplayName/displayName in the response for groups, if permitted (e.g. Directory.Read.All).