Monday, October 10, 2016

Create Azure AD group and set group owner using Microsoft Graph Client library

In one of my previous posts I wrote about basic configuration steps needed for working with Azure AD via Microsoft Graph Client library (Work with Azure AD via Microsoft Graph API). These steps included registering app within Azure AD and creating authentication provider for authenticating requests with client id and secret from registered app. In this post I will show how to create Azure AD group and set it’s owner programmatically. We will use the same AzureAuthenticationProvider which we used in previous example:

   1: static async void createGroupWithOwner()
   2: {
   3:     var graph = new GraphServiceClient(new AzureAuthenticationProvider());
   4:     try
   5:     {
   6:         string groupName = string.Format("NewGroup-{0}",
   7:             DateTime.Now.ToString("yyyy-MM-dd_HH_mm"));
   8:  
   9:         var groupInfo = new Group();
  10:         groupInfo.DisplayName = groupName;
  11:         groupInfo.MailEnabled = false;
  12:         groupInfo.MailNickname = groupName;
  13:         groupInfo.SecurityEnabled = true;
  14:  
  15:         var group = await graph.Groups.Request().AddAsync(groupInfo);
  16:  
  17:         User owner = null;
  18:         var users = await graph.Users.Request().GetAsync();
  19:         foreach (var u in users)
  20:         {
  21:             if (u.UserPrincipalName.Contains("username@example.com"))
  22:             {
  23:                 owner = u;
  24:                 break;
  25:             }
  26:         }
  27:         
  28:         if (user == null)
  29:         {
  30:             return;
  31:         }
  32:  
  33:         await graph.Groups[group.Id].Owners.References
  34:             .Request().AddAsync(owner);
  35:     }
  36:     catch (ServiceException x)
  37:     {
  38:         Console.WriteLine("Exception occured: {0}", x.Error);
  39:     }
  40: }
  41:  
  42:  
  43:  
  44: public class AzureAuthenticationProvider : IAuthenticationProvider
  45: {
  46:     public async Task AuthenticateRequestAsync(HttpRequestMessage request)
  47:     {
  48:         string clientId = ConfigurationManager.AppSettings["ClientId"];
  49:         string clientSecret = ConfigurationManager.AppSettings["ClientSecret"];
  50:         string authority = ConfigurationManager.AppSettings["AuthorityUrl"];
  51:     
  52:         AuthenticationContext authContext = new AuthenticationContext(authority);
  53:     
  54:         ClientCredential creds = new ClientCredential(clientId, clientSecret);
  55:     
  56:         Console.WriteLine("before: get token");
  57:         AuthenticationResult authResult =
  58: await authContext.AcquireTokenAsync("https://graph.microsoft.com/", creds);
  59:         Console.WriteLine("after: get token {0}", authResult.AccessToken);
  60:     
  61:         request.Headers.Add("Authorization", "Bearer " + authResult.AccessToken);
  62:     }
  63: }

At first we create group (lines 6-15) and add time stamp to the group name (although there may be groups in Azure AD with the same display name, for clearance distinguish them by name). After that we find user by email (lines 17-26) and finally add this user to groups owners (lines 28-34). For convenience I also added here code of AzureAuthenticationProvider from previous example.

No comments:

Post a Comment