Wednesday, 12 July 2017

Add or Remove member from a Group using Microsoft Graph .NET Client Library

Managing Group membership of Azure AD Group and Office 365 Group is one of a routine task for every Office 365 Admin. We can easily add or remove user from group using Microsoft Graph api. In this post, I am going to share C# .NET Client Library code to add and remove membership of an user.

Add member to a Group using Microsoft Graph .NET SDK:

private static void AddGroupMember(string groupId, User user) 
{ 
  var client = new GraphServiceClient(new DelegateAuthenticationProvider( 
      (requestMessage) => 
      { 
          requestMessage.Headers.Add("Authorization", "Bearer " + "<Access Token>"); 
          return Task.FromResult(0); 
  
      })); 

  client.Groups[groupId].Members.References.Request().AddAsync(user); 
}
For more info : Add member - Documentation - Microsoft Graph

Remove member from a Group using Microsoft Graph C# Client Library:

private static void RemoveGroupMember(string groupId, string memberId) 
{ 
  var client = new GraphServiceClient(new DelegateAuthenticationProvider( 
      (requestMessage) => 
      { 
          requestMessage.Headers.Add("Authorization", "Bearer " + "<Access Token>"); 
          return Task.FromResult(0); 
  
      })); 

 client.Groups[groupId].Members[memberId].Reference.Request().DeleteAsync(); 
}
For more info: Remove member - Documentation - Microsoft Graph