Getting group users using UnifiedGroupsUtility Class

Jun 3, 2019 | Blog | 0 comments

PnP Core online framework provides a fantastic class called “UnifiedGroupsUtility” which has several methods related to groups. It uses Graph Service to do all the operations. In this post we will be looking into to how to get the users in a particular group.

High level steps

In order to get the users in a group we need to do the following:

  1. Register an application Azure AD
  2. Provide required permissions (Group.Read.All and User.Read.All) to that application registration
  3. Create a client secret for the application registration
  4. Get the access token using “AcquireTokenAsync” method
  5. Call the “GetUnifiedGroupMembers” method of the “UnifiedGroupsUtility” class

Application registration

Registering an application is needed to access services in Azure AD. More information on application registration can be found here.

An application registration can be created manually using the Azure portal or can be done with commands using Azure CLI (more details on this in Vardhaman Deshpande’s blog). We will use the Azure CLI in this case.

You can download the latest version of Azure CLI from here.

Once downloaded, open PowerShell and run the following command

az login

Follow the instructions to login to Azure and then run the following

$uniqueGUID = [System.Guid]::NewGuid().ToString()

Permissions for the app registration

On your machine, create a file named “manifest.json” with the following json and copy the path of the json file.

[
   {
      "resourceAppId":"00000003-0000-0000-c000-000000000000",
      "resourceAccess":[
         {
            "id":"5b567255-7703-4780-807c-7be8301ae99b",
            "type":"Role"
         },
         {
            "id":"df021288-bdef-4463-88db-98f22de89214",
            "type":"Role"
         }
      ]
   }
]

 

Run the following command to create an app registration

az ad app create  --display-name "App Reg Display Name" --homepage
"https://localhost"  --identifier-uris https://app_reg_name/$uniqueGUID - -required-
resource-accesses .\manifest.json

 

From the output in PowerShell window grab the ID (objectId) of the application registration and run the following command

az ad app permission admin-consent  --id "ID of the application"

 

The above command grants the app registration the required permissions on behalf of the administrator.

Client Id and Client secret

To get the access token we need to have the Client Id, the Client Secret of the app registration created above. To get those, navigate to the azure portal click on “Azure Active Directory” and then on “App Registrations”

Azure AD Portal

Azure AD Portal

Click on “All applications” tab and select the app registration created in the previous step.

Copy the “Client Id” (Application Id) from the “Overview” blade.

Azure AD Client ID

Azure AD Client ID

Click on “Certificates & secretes” and click on “+ New client secret” and specify the required details — Description and expiry. After that click on “Add” and copy the client secret to a safe place. Once we navigate away from this page the client secret will not be visible. (In that case we will have to create new client secret).

Azure AD Certificates and Secrets

Azure AD Certificates and Secrets

Getting the access token

Once we have the client id and client secret we can get the access token easily (thanks to Microsoft.IdentityModel) using the method “AcquireTokenAsync” on the “AuthenticationContext” object.

public static async Task GetMSGraphAccessToken()
{
    string authority = string.Format(CultureInfo.InvariantCulture, "{0}/{1}/",
"https://login.windows.net", "yourtenantname.onmicrosoft.com");
    var authContext = new AuthenticationContext(authority);

    string clientId = "client_id_copied_earlier";
    string clientSecret = "client_secret_copied_earlier";

    var clientCredential = new ClientCredential(clientId, clientSecret);
    var result = await authContext.AcquireTokenAsync("https://graph.microsoft.com",
clientCredential);

    var accessToken = result.AccessToken;
    return accessToken;
}

 

Getting the group members

As I have said in my previous blog posts, PnP is an awesome community and the repositories they have are really cool. One of the classes from the PnP Sites Core repository is “UnifiedGroupsUtility” and this class has various methods related to groups.

In this case we will be using “GetUnifiedGroup” and “GetUnifiedGroupMembers” methods. We would need the id of the group for this and this can be obtained from Azure Active Directory (Azure portal > Azure Active Directory > Groups > Required Group > Object Id)

public static async void GetGroupMembers(string requiredGroupId)
{
    string accessToken = await GetMSGraphAccessToken();
    var requiredGroup = UnifiedGroupsUtility.GetUnifiedGroup(requiredGroupId,
accessToken);
    var requiredGroupMembers =
UnifiedGroupsUtility.GetUnifiedGroupMembers(requiredGroup, accessToken);

    foreach (var member in requiredGroupMembers)
    {
        Console.WriteLine(member.UserPrincipalName);
    }
}

 

That’s how easy it is to get the group members using the UnifiedGroupsUtility class.

Note: Currently, this method works only for non-nested groups.

RELATED POSTS:

7 tips for Microsoft Teams adoption

Teams represents a new way of working. It’s a modern communications and collaboration platform. It’s a hub for channel and thread-based conversations. It supports live and streamed events. File-sharing and real-time instant chat. All of this surfaced in a single user...

read more

What is Microsoft Managed Desktop?

Microsoft Managed Desktop (MMD) provides the best experience for users managed by Microsoft. MMD is a subscription-based service which can help to overcome business challenges such as coming away from complex Legacy systems which are making digital transformation too...

read more