15

I've been investigating how to add (and later remove) a user from an Azure AD group using the Microsoft Graph API (the dotnet/C# library available on nuget).

Nuget MS Graph API

Ignoring all else around getting a connected GraphServiceClient etc. I'm trying code very similar to the sample below, not getting any exception (suggesting things are fine) but when I get the group once again via the API, it's not got any members still!

Quickwatch of returned group object after modification attempt

Interestingly (as an aside), when I ask for memberOf property on the user object and tell it to expand it, it comes back null still.

var user = await client.Users[userPrincipalName]
             .Request()
               .Select("id,memberOf")
                 .Expand("memberOf")
                   .GetAsync();

var group = await client.Groups[groupId]
              .Request()
                .Select("members")
                  .Expand("members")
                    .GetAsync();

group.Members.Add(user);

await client.Groups[groupId].Request().UpdateAsync(group);

// userPrincipalName => "[email protected]"
// groupId => the object GUID for the group

Does anyone know what I'm doing wrong here? The docs I used to come up with this code were based on the links to the following documents:

API doc for 'group'

Adding a member to a group

Also, I tried to style the approach on the solution suggested here to setting licenses for users:

Assign user license via Graph API

As usual, thanks for any help.

Peter

Additional

I've also tried poking around in the graph API looking at potentially updating the .Members property/resource rather than the group itself:

await client.Groups[groupId].Members.Request(). // <-- Only has GetAsync()

But it only has the GetAync() method available to it.

Updated based on answer

var usersGroups = await client.Users[userPrincipalName].MemberOf.Request().GetAsync();

if (!usersGroups.Any(g => g is Group && g.Id == groupId))
{
    // User is not a member of the group, add them.
    var user = await client.Users[userPrincipalName].Request().Select("id").GetAsync();
    await client.Groups[groupId].Members.References.Request().AddAsync(user);
}

I've added the code snippet above based on the answer, as I think it succinctly answers the issue regarding adding members.

Thanks to Nan Yu for the answer.

1 Answer 1

23
+50

To add user to Group ,you could use :

User userToAdd = await graphClient.Users["objectID"].Request().GetAsync(); 
await graphClient.Groups["groupObjectID"].Members.References.Request().AddAsync(userToAdd);

To get members of a group :

        List<ResultsItem> items = new List<ResultsItem>();

        // Get group members. 
        IGroupMembersCollectionWithReferencesPage members = await graphClient.Groups[id].Members.Request().GetAsync();

        if (members?.Count > 0)
        {
            foreach (User user in members)
            {
                // Get member properties.
                items.Add(new ResultsItem
                {
                    Properties = new Dictionary<string, object>
                    {
                        { Resource.Prop_Upn, user.UserPrincipalName },
                        { Resource.Prop_Id, user.Id }
                    }
                });
            }
        }

Get groups the current user is a direct member of ,you could try :

IUserMemberOfCollectionWithReferencesPage memberOfGroups = await graphClient.Users["[email protected]"].MemberOf.Request().GetAsync();

            if (memberOfGroups?.Count > 0)
            {
                foreach (var directoryObject in memberOfGroups)
                {

                    // We only want groups, so ignore DirectoryRole objects.
                    if (directoryObject is Group)
                    {
                        Group group = directoryObject as Group;
                        items.Add(new ResultsItem
                        {
                            Display = group.DisplayName,
                            Id = group.Id
                        });
                    }

                }
            }
Sign up to request clarification or add additional context in comments.

3 Comments

I've never seen this "GroupService" before, but the other stuff seems to make sense/work! :)
sorry , i thought you are using github.com/microsoftgraph/aspnet-snippets-sample . In that code sample , there is a GroupService class . If you are not using that code sample . you could use IGroupMembersCollectionWithReferencesPage members = await graphClient.Groups[id].Members.Request().GetAsync(); to get group members . Please check edited answer .

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.