Get Azure AD (Entra ID) App-Only Access Token with PowerShell

In this blog post, we will explore how to obtain an Access Token for Application Permissions to access specific resources (ex: Microsoft Graph) without user involvement in PowerShell. We’ll use the OAuth client credentials grant flow to acquire a token on behalf of an Azure AD (Microsoft Entra ID) application.

This method, also known as app-only token acquisition, involves obtaining an access token through a silent or non-interactive mode. This approach proves particularly convenient for background services (daemons) and PowerShell scripts, offering a straightforward means of acquiring tokens without requiring user interaction.

When authenticating as an application (as opposed to with a user), the delegated permissions set up in the app won’t be applied since there is no user for the application to represent. You must configure the required application permissions (app roles) for a resource (ex: Microsoft Graph) and grant admin consent. If you wish to obtain a token with delegated permissions, you can refer to this post: Retrieve Access Token with Delegated Permissions.

Get (or Create) your Azure AD (Microsoft Entra ID) Application Details

This article assumes that you already have an Azure AD (Microsoft Entra ID) Application and its details, such as the Application (Client) ID, Client Secret, or Client Certificate. If you don’t have an existing application, please refer to this post for guidance on Creating and Configuring an Azure AD application in Microsoft Entra ID (Azure AD Portal).

Once your Azure AD App is ready, ensure that the required admin consent is granted for the application permissions (app roles) set up within the application. For detailed instructions, refer to this post: How to configure permissions and grant admin consent.

As we intend to utilize the app in PowerShell, implementing a custom flow for consent is not feasible. Therefore,  admin consent should have already been granted for your client application from the Microsoft Enta Admin Center (Azure AD portal).

Alternatively, you (or your directory admin) can also provide consent by pasting the following URL in a browser. Replace the Application client ID (client_id) with your app’s client ID.

https://login.microsoftonline.com/common/adminconsent?client_id=635fb059-9ff3-47b6-9bfb-4f1264799865&state=12345&redirect_uri=https://login.microsoftonline.com/common/oauth2/nativeclient

Note: If the redirect_uri for the native client is not configured in your application, the consent will be granted successfully. However, you might encounter an issue with redirection after successfully granting consent. This error can be ignored as long as the URL includes admin_consent=True.

Get App-Only Access Token with Client Secret using Invoke-RestAPI

After setting up the Azure AD application with the necessary permissions, retrieve the application details, including Client ID, Client Secret, and Tenant ID. Replace these details and execute the following command to generate a token to access the Microsoft Graph resource API with the configured Application permissions.

#Provide your Office 365 Tenant Domain Name or Tenant Id
$TenantId = "contoso.onmicrosoft.com"
#$TenantId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
 
#Provide Application (client) Id of your app
$AppClientId="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
  
#Provide Application client secret key
$ClientSecret ="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
  
$RequestBody = @{client_id=$AppClientId;client_secret=$ClientSecret;grant_type="client_credentials";scope="https://graph.microsoft.com/.default";}
$OAuthResponse = Invoke-RestMethod -Method Post -Uri https://login.microsoftonline.com/$TenantId/oauth2/v2.0/token -Body $RequestBody
$AccessToken = $OAuthResponse.access_token

Install MSAL.PS Module

MSAL.PS is an authentication library that helps you to obtain tokens from Azure AD (Microsoft Enterprise ID) for accessing secured Microsoft APIs, including Microsoft Graph, SharePoint Online, Microsoft Power Automate, and others, for both Delegated and Application permissions.

Run the following command to install the MSAL.PS module from PowerShell Gallery.

Install-Module -Name MSAL.PS

Once you have installed the module, you can use the built-in help commands in PowerShell to learn about each command in the module.

## View usage examples.
Get-Help Get-MsalToken -Examples
 
## View full help.
Get-Help Get-MsalToken –Full

Get App-Only Access Token with Client Secret using MSAL.PS Library

After installing the MSAL.PS module, run the following command to obtain an access token using Password-Based Authentication (client app secret). This flow silently retrieves the token without any user interaction in PowerShell.

#Provide your Office 365 Tenant Domain Name or Tenant Id
$TenantId = "contoso.onmicrosoft.com"
#$TenantId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
 
#Provide Application (client) Id of your app
$AppClientId="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
  
#Provide Application client secret key
$ClientSecret ="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxx" | ConvertTo-SecureString -AsPlainText -Force


$MsalResponse = Get-MsalToken -Scopes 'https://graph.microsoft.com/.default' -TenantId $TenantId -ClientId $AppClientId -ClientSecret $ClientSecret 

$AccessToken = $MsalResponse.AccessToken

Get App-Only Access Token with Certificate-Based Authentication

Microsoft Entra ID (Azure AD) provides support for certificate-based authentication in addition to password-based authentication (app secret) for accessing resource APIs with secured mode. You can generate your own self-signed public certificate and use it for authentication. Alternatively, you can obtain a signed certificate from a Certificate Authority (CA). For additional details, please read this article: Create a self-signed public certificate to authenticate your application.

In this guide, we will create and export a self-signed certificate and upload the certificate into the Azure AD application. Run the following command in PowerShell to create and export a new self-signed certificate.

## Create your public certificate
$certname = "MEIAppCert1"    ## Replace certificate name if needed
$cert = New-SelfSignedCertificate -Subject "CN=$certname" -CertStoreLocation "Cert:\CurrentUser\My" -KeyExportPolicy Exportable -KeySpec Signature -KeyLength 2048 -KeyAlgorithm RSA -HashAlgorithm SHA256

## Exports the certificate in .cer format
Export-Certificate -Cert $cert -FilePath "C:\Temp\$certname.cer"   ## Specify your preferred location.

Now, we have generated a certificate and stored it in the current user’s certificate store. Also, we have exported the certificate into a custom local location (C:\Temp\MEIAppCert1.cer). You can now upload the exported certificate file (MEIAppCert1.cer) to your client application in the Azure AD Portal (Microsoft Entra admin center). Once uploaded, retrieve the certificate thumbprint, which you can use to authenticate your application.

Run the following command after substituting the TenantId, ClientId, and Certificate Thumbprint details to acquire an app-only access token using certificate-based authentication.

#Provide your Office 365 Tenant Domain Name or Tenant Id
$TenantId = "contoso.onmicrosoft.com"
#$TenantId = "xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
 
#Provide Application (client) Id of your app
$AppClientId="XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX"
  
#Load Certificate from current user's Certificate store - specify thumbprint of your certificate 
$ClientCertificate = Get-Item Cert:\CurrentUser\My\XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
#$ClientCertificate = Get-Item Cert:\CurrentUser\My\{CertificateThumbprint} 


$MsalResponse = Get-MsalToken -Scopes 'https://graph.microsoft.com/.default' -TenantId $TenantId -ClientId $AppClientId -ClientCertificate $ClientCertificate 

$AccessToken = $MsalResponse.AccessToken

In the provided examples, we are fetching the token for the Microsoft Graph resource API. Adjust the value in the Scopes parameter to obtain a token for other Microsoft-supported resources like SharePoint, Yammer, Intune, Power BI, and additional services.

Use the Access Token to call Microsoft Graph API

After acquiring the necessary Access Token, utilize the Invoke-RestMethod cmdlet to invoke the Rest API using the obtained access token in PowerShell. The following command calls the list users endpoint within the Microsoft Graph API resource, fetching information about Microsoft 365 users.

#Provide your access token 
#$AccessToken="eyJ0eXAiOiJ......" 
   
#Form request headers with the acquired $AccessToken
$headers = @{'Content-Type'="application\json";'Authorization'="Bearer $AccessToken"}
   
#This request gets all users list
$ApiUrl = "https://graph.microsoft.com/v1.0/users"
  
$Response = Invoke-RestMethod -Method GET -Uri $ApiUrl -ContentType "application\json" -Headers $headers
$Users = $Response.value
Advertisement

Leave a Comment