Office 365 – Microsoft Graph – Part 5 – Fetching Office 365 group owners using CSOM – Codebase

Office 365 - Microsoft Graph - CodeBase to fetch the count of Owner of the groups

Hi All,

In last article we discussed about fetching all Office 365 groups, in this article we will go one step ahead – we will discuss about fetching the respective group owners. We will discuss about one simple use case.

Let’s continue our Microsoft Graph show 😊

In last article “Office 365 – Microsoft Graph – Part 4 – Fetching all Office 365 groups using CSOM- Codebase” we went through the CSOM code base to fetch all Office 365 groups. We had simple use case and went through all steps.

If you missed the previous articles in this series, here is the list, please have a look once.

Office 365 – Microsoft Graph and Graph Explorer
Office 365 – Azure Active Directory – Registering/Creating new Azure App – detailed steps
Office 365 – Microsoft Graph beginning – Part 1
Office 365 – Microsoft Graph – Part 2 – Granting permission to Azure Apps to use Microsoft Graph APIs using CSOM
Office 365 – Microsoft Graph – Part 3 – Azure Access Token: to call Graph APIs from CSOM
Office 365 – Microsoft Graph – Part 4 – Fetching all Office 365 groups using CSOM- Codebase

In this article we will go through another use case.

Use Case: For our Office 365 tenant, we have some governance policies in place. One of our policy is to make sure for every modern team site in tenant we have at least minimum two site collection administrators. If there are less than two admins then need to send email to one of the admin. If there is no admin at all to the site then email need to send to Global Administrator of the tenant.

Approach: We planned to write again job (either through Azure Web Job or Console Application), which will go through all the Office 365 groups and check the Group Owners count. In this article we will discuss by creating console application using Visual Studio 2017 and get the Office 365 group owners using CSOM.

Important Point: Here, please note that we are not going through the Modern Team Sites and verifying the Site Collection Administrators. We will go through the Office 365 group which created behind the scene when Modern Team site is get created.

Let’s begin the show 😊.

 In last article we have detailed steps. In this article we will directly go through the require code base.

Following are the detailed steps:

Start the Visual Studio 2017, create console application, let’s say “knowledge-junction” as

Fig 1: Office 365 – Microsoft Graph – Console Application – to verify all Office 365 groups owners

Install following require packages using NuGet manager – for details please go through last article once.

  1. Microsoft Graph
  2. Microsoft Identity Client Active Directory

Once we have required packages are in place, we can call “Microsoft Graph” APIs.

Most important step – to call respective Graph API we need “Azure Access Token”, we need to add “Azure Access Token” to the header of HttpRequestMessage request object.

We need to override the method – AuthenticateRequestAsync(HttpRequestMessage request) from IAuthenticationProvider interface. We discussed this in one of our previous article “Office 365 – Microsoft Graph – Part 3 – Azure Access Token: to call Graph APIs from CSOM” To achieve this we will add new class in our solution which will be derived from IAuthenticationProvider as

using Microsoft.Graph;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System.Net.Http;
using System.Threading.Tasks;

namespace knowledge_junction
    class AuthenticationProvider : IAuthenticationProvider
        /// <summary>
        /// Method to set the access token to HttpRequestMessage header
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public async Task AuthenticateRequestAsync(HttpRequestMessage request)
            //Azure App ID
            string clientId = "<AZURE APP ID>";
            string clientSecretKey = "<CLIENT SECRET KEY>";
            string authority = "<TENANT ID>";

            AuthenticationContext authenticationContext = new AuthenticationContext(authority);
            ClientCredential clientCredential = new ClientCredential(clientId, clientSecretKey);
            AuthenticationResult authResult = await authenticationContext.AcquireTokenAsync("", clientCredential);
            //Setting the token in header of HttpRequestMessage object
            request.Headers.Add("Authorization", "Bearer " + authResult.AccessToken);

Fig 2: Office 365 – Microsoft Graph – Overriding “AuthenticateRequestAsync” method from IAuthenticationProvider

Next step is to create instance of GraphServiceClient, this class is part of “Microsoft Graph” library as

GraphServiceClient graphServiceClient = new GraphServiceClient(new AuthenticationProvider());

Once we have instance of GraphServiceClient instance ready we can fetch groups and respective owners as

Getting all groups: Here we will get the groups, we are again fetching only of first page

#region to get all Office 365 groups
            IGraphServiceGroupsCollectionPage graphServiceGroupsCollectionPage = null;
            IList<Group> groups = new List<Group>();

            Task.Run(async () =>
                    //Requesting groups
                    graphServiceGroupsCollectionPage = await graphServiceClient.Groups.Request().GetAsync();
                    //getting groups only from current page / first page
                    groups = graphServiceGroupsCollectionPage.CurrentPage;
                catch (Exception _ex)

Figure 3: Office 365 – Microsoft Graph – CodeBase to fetch all Office 365 groups using CSOM

Once we have all the groups in place, for every group we can fetch group owners as

#region Code to get the group owners count
            //QueryOption class - querying for only two admins
            QueryOption queryOption = new QueryOption("$top", "2");
            Microsoft.Graph.IGroupOwnersCollectionWithReferencesPage owners = null;

            //iterating throug all groups on first page
            foreach (Group group in groups)
                Task.Run(async () =>
                    //Requesting top two owners for the group
                    owners = await graphServiceClient.Groups[group.Id].Owners.Request(new Option[] { queryOption }).GetAsync();
                //displaying group name and respective owners count
                Console.WriteLine(group.DisplayName + " - " + owners.Count);

Figure 4: Office 365 – Microsoft Graph – CodeBase to fetch the count of Owner of the groups

Once we have count of group owners, we can check whether there are two groups owners available or not and if not then we can send email to respective primary group owner or global administrator of the tenant.

Thanks for reading 😊

Keep reading, share your thoughts, experiences. Feel free to contact us to discuss more. If you have any suggestion / feedback / doubt, you are most welcome.

Stay tuned on Knowledge-Junction, will come up with more such articles

One thought on “Office 365 – Microsoft Graph – Part 5 – Fetching Office 365 group owners using CSOM – Codebase

This site uses Akismet to reduce spam. Learn how your comment data is processed.