A colleague recently asked me how to access the Microsoft Graph API using PowerShell without specifying his user account or credentials. So here’s a little post about the required configuration to authenticate against the OAuth 2.0 endpoint of Azure AD with an app registration. This is especially useful for automation services like Azure automation.

At the end of this post you’ll find a PowerShell template.

Gather application information

Create a new client secret for your app and note down the following values:

  • Client Secret
  • Application ID (client ID)
  • Directory ID (tenant ID)
Azure AD App registration
## PowerShell code

Request authentication token

In order to use the Graph API we need an authentication token. The information we gathered before is now sent to the Azure AD OAuth 2.0 endpoint.

1
https://login.microsoftonline.com/{TenantID}/oauth2/v2.0/token

In the request supply a body with the following content:

1
2
3
4
5
6
$body=@{
    client_id="8f9f420d-606c-4e13-889e-837072dbfb42"
    client_secret="BlaBlaExampleSecret" #Generated secret
    scope="https://graph.microsoft.com/.default"
    grant_type="client_credentials"
}

The scope and grant_type are required attributes. A full example looks like:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
$body=@{
    client_id="8f9f420d-606c-4e13-889e-837072dbfb42"
    client_secret="BlaBlaExampleSecret"
    scope="https://graph.microsoft.com/.default"
    grant_type="client_credentials"
}

$tenantId="7955e1b3-cbad-49eb-9a84-e14aed7f3400"

Invoke-WebRequest -Uri "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token" -ContentType "application/x-www-form-urlencoded" -Body $body -Method Post

If everything works we receive an access token object as HTML 200/ok response:

HTTP response

Using the access token

Now you’re ready to make requests to the Graph API. Just include the access token in your request’s header. Make sure that your application has the required permissions assigned and granted with admin consent!

API permissions

PowerShell template

Here’s a little PowerShell template which contains all the logic required to authenticate against the Graph API - hope it saves you some time: