Calling the Microsoft Graph API via PowerShell without a user

1 minute read

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.{TenantID}/oauth2/v2.0/token

In the request supply a body with the following content:

    client_secret="BlaBlaExampleSecret" #Generated secret

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



Invoke-WebRequest -Uri "$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: