In a recent project, we needed to updated members of an existing Office 365 group using Microsoft Graph Client CSOM. Previously in a blog here, I have listed a way to add members using Office 365 PnP CSOM (UnifiedGroupUtility) but there is an ongoing issue with it in the recent releases . So in the meantime while that issue is fixed, we could use the below method to update owners or members in O365 groups.

Steps:

  1. Create a Graph app. The steps for doing that is listed in this blog.
  2. Get the Authentication token of the App
  3. Get the list of owner emails and add them to a list array
  4. Call the Graph Client to authenticate using the authentication token
  5. Traverse the owners emails array and validate the user using the Graph users collection
  6. Add the user to the members and owners of the Office 365 group

Note: For Office 365 group owners, the users should be a part of the members and the owners groups.

Below is the code snippet for the same.

Happy Coding !!!

using OfficeDevPnP.Core.Framework.Graph;
using Microsoft.Graph;
using Microsoft.SharePoint.Client;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
var authenticationContext = new AuthenticationContext(authString, false);
// Config for OAuth client credentials
ClientCredential clientCred = new ClientCredential(clientId, clientSecret);
AuthenticationResult authenticationResult = null;
string token = "";
Task authtask = Task.Run(async () => authenticationResult = await authenticationContext.AcquireTokenAsync(resourceId, clientCred));
authtask.Wait();
//List of Owner Emails
List<string> Owners = new List<string>();
if (authenticationResult != null)
{
token = authenticationResult.AccessToken;
var group = UnifiedGroupsUtility.ListUnifiedGroups(token, mailNickname: alias).Where(result => result.MailNickname.ToLower().Equals(alias.ToLower())).First();
if (group != null)
{
string groupId = group.GroupId;
if (Owners.Count > 0)
try
{
Task runTask = Task.Run(async() => await updateGroupOwner(token, groupId, assetOwners));
runTask.Wait();
}
catch(Exception ex)
{
log.Info("Exception while adding owners " + ex.Message);
}
}
}
private async Task updateGroupOwner(string token, string groupId, List<string> assetOwners)
{
GraphServiceClient graphClient = new GraphServiceClient(new DelegateAuthenticationProvider(
async (requestMessage) =>
{
if (!String.IsNullOrEmpty(token))
{
// Configure the HTTP bearer Authorization Header
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
}
}), new PnPHttpProvider(10, 500));
var groupToUpdate = await graphClient.Groups[groupId].Request().GetAsync();
foreach (var o in Owners)
{
var ownerQuery = await graphClient.Users
.Request()
.Filter($"userPrincipalName eq '{o}'")
.GetAsync();
var owner = ownerQuery.FirstOrDefault();
if (owner != null)
{
try
{
// And if any, add it to the collection of group's owners and members
await graphClient.Groups[groupToUpdate.Id].Members.References.Request().AddAsync(owner);
await graphClient.Groups[groupToUpdate.Id].Owners.References.Request().AddAsync(owner);
}
catch (ServiceException ex)
{
if (ex.Error.Code == "Request_BadRequest" &&
ex.Error.Message.Contains("added object references already exist"))
{
// Skip any already existing owner
}
else
{
throw ex;
}
}
}
}
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s