Search code examples
c#active-directorymicrosoft-graph-apimicrosoft-graph-sdks

How can I get a list of AD user groups along with AD user with Microsoft Graph SDK


The code:

            var users = await graphClient.Users
            .Request()
            .Filter("startswith(userPrincipalName, '" + userPrincipalName + "')")
            .Select(u => new { u.Id, u.OtherMails, u.DisplayName, u.UserPrincipalName, u.MemberOf })
            .GetAsync();

returns a null for MemberOf. I know I can do a subsequent:

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

but I'd rather return a Microsoft.Graph.User class type with all the info.


Solution

  • The memberOf is not a property but a relationship and you can get the relationship's data by using expand query parameter. See the below API call and its result.

    https://graph.microsoft.com/v1.0/users?$filter=startswith(userPrincipalName,'Shiva@nishantsingh.live')&$select=id, displayName, memberOf&$expand=memberOf

    enter image description here

    So, use the code something like this.

    var users = await graphClient.Users
                .Request()
                .Filter("startswith(userPrincipalName, '" + userPrincipalName + "')")
                .Select(u => new { u.Id, u.OtherMails, u.DisplayName, u.UserPrincipalName, u.MemberOf })
                .Expand(d => d.memberOf)
                .GetAsync();