Patrick Lamber

Patrick Lamber - Jan 29, 2018 - Follow          
Technical consultant and Office Server and Services MVP.

How do I authenticate towards Graph API with PowerShell?

The post "How do I authenticate towards Graph API with PowerShell?" is a post of a post series. Find below all posts associated to this post series.
by Patrick Lamber on Jan 29, 2018
Filed under: Graph API Scripts Office 365
Share it:

The Graph Explorer is a good way to play around with the Graph API endpoints without worrying about how the authentication process has to be performed towards your environment. On the other hand, our aim is to write PowerShell scripts which perform operations against our resources in an autonomous way. This can be done after we understood how to identify ourselves, ensure that we have proper permissions, and perform the desired operations.

How do we identify ourselves?

Operations performed towards our environment have to happen with an authenticated identity. This is also true for our scripts that want to perform operations in an autonomous way. Our scripts can be uniquely identified on Azure AD associated with our Office 365 tenant. Usually, I am registering a new application using the Azure Portal.

Every application has an unique Application ID. An Application ID is like the username of your application. The password of the application can either be an SSL certificate or a Secret key. We are going to use the second option for our scripts.

What I am allowed to perform?

With both Application ID and Secret you are able to identify yourself towards your environment. This does not mean, however, that your application is allowed to perform any operation. We need to ensure that the application is allowed to perform the desired action by having proper permissinos assigned.

The Graph API endpoints return an access denied error message if you fail to configure the right permissions for your application.

The permissions can either run delegated or as application permissions. More details about these two modes can be found here. Our major aim with the PowerShell script is to run automated maintenance activities. These operations are typically running on a wider scope without user context and require therefore application scoped permissions.

Show me an example - getting all users in your tenant

Let us take the documentation on how to enumerate all users with the Graph API. If you want to consume other endpoints just follow the steps described here.

  • Register a new Azure AD app or re-use an existing app
  • Assign the desired permissions to your Azure AD application
  • Take the values and consume the API with PowerShell
You can find the documentation of the available Graph API endpoints with the required permissions here.

Register a new Azure AD app

The registration of an application in Azure AD can be performed using the Azure Portal.

  • Login to Azure Portal using your admin credentials
  • choose More Services, click App Registrations, and click New application registration
  • Specify a name and a Sign-on URL. You can put any value in the Sign-on URL. Our PowerShell script will not rely on it.
  • Once you've completed registration, Azure AD assigns your application a unique client identifier, the Application ID.

You have now a registered application with a unique Application ID. Now, let us go and create the Client Secret (Application Password) for our script.

  • Choose Settings from your application overview.
  • Choose Keys and add a new key. When hitting save your Client Secret will be displayed. Save the value immediately because it will no more show up.

The next picture shows how you could assign a Client Secret to your application. You can have multiple Secret Keys assigned to your application with or without expiration date.

Assign the right permissions to your app

With the Application ID and Client Secret alone you are not able to perform a lot of activities. We need to ensure that your application has the right priviledges to perform the desired action. We said that our scripts will run in the conext of an application, therefore, we need to identify what permission is required to run the retrieval of our users.

Now go and open the documentation for retrieving users. You can see that it shows you that we will consume the endpoint GET /users. This means that our URL will be Furthermore, the page shows you that the code running in the Application scope requires at least User.Read.All permissions. We need to ensure that the application will have these priviledges assigned. Go to the application settings and follow these steps.

  • Choose Settings from your application overview.
  • Choose Required permissions and choose Add.
  • Select an API and choose Microsoft Graph
  • Under application permissions choose "Read all users' full profiles"
  • Confirm until you see a screen similar like the picture shown below. REmember to press the Grant Permissions button to ensure permissions are properly propagated.

Now it is time to consume some data

We have the Client ID and Secret and the correct permissions to perform the activities. The script presented below is going to perform the authentication against our tenant. We will use the Microsoft.IdentityModel.Clients.ActiveDirectory.dll to retrieve the authentication token required to perform our actions.

You need to install the Microsoft.IdentityModel.Clients.ActiveDirectory pacakge following this link.
You also need to get the tenant ID of your environment. You can follow the necessary steps following this link.

Now let us see the code.

# this is the path to the Microsoft.IdentityModel.Clients.ActiveDirectory.dll on my environment. Ensure that you have the proper path set

Add-Type -Path 'C:\Program Files\WindowsPowerShell\Modules\AzureAD\Microsoft.IdentityModel.Clients.ActiveDirectory.dll'

$tenantID = "specifyYourTenantIdHere"
$authString = "$tenantID" 

$appId = "putYourApplicationIdHere"
$appSecret = "putYourClientSecretHere"

# this part uses the classes to obtain the necessary security token for performing our operations against the Graph API

$creds = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.ClientCredential" -ArgumentList $appId, $appSecret
$authContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext"-ArgumentList $authString
$context = $authContext.AcquireTokenAsync("", $creds).Result

# this is the endpoint used to get all users

$url = ""
# the endpoint described by Microsoft requires a GET operation with the correct authorization headers

$query = Invoke-RestMethod -Method Get -Headers @{
            Authorization   = $context.CreateAuthorizationHeader()
            'Content-Type'  = "application/json"
        } -Uri $url

# paginated results will be retrieved here. I will show you in a different post how to go through all the users

by Patrick Lamber on Jan 29, 2018
Filed under: Graph API Scripts Office 365
Share it:
The post "How do I authenticate towards Graph API with PowerShell?" is a post of a post series. Find below all posts associated to this post series.