Working with Microsoft Graph API using PowerShell part 2: Getting an Access Token

IMPORTANT:
Cloud Modernization Notice (2026):
The original version of this post loaded ADAL DLLs from the AzureAD module and acquired tokens with a username and password (ROPC flow). ADAL and the AzureAD module are both retired, and password-based token acquisition fails for any account protected by MFA. This post has been rewritten with supported methods. The original code is kept at the bottom for reference.

This is the second post in my Microsoft Graph series. In part 1 we registered an application in Entra ID. In this post we get an access token and use it to call Microsoft Graph.

There are three supported ways to do this from PowerShell today. Pick the one that matches your scenario:

ScenarioMethod
Admin running scripts interactivelyOption 1: Connect-MgGraph delegated sign-in
Scheduled / unattended automationOption 2: Connect-MgGraph app-only with a certificate
No modules allowed, or calling Graph from other toolsOption 3: Raw REST client-credentials token

Option 1: Delegated Sign-In with Connect-MgGraph

The Microsoft Graph PowerShell SDK handles MSAL, token caching, and refresh for you. You sign in as yourself (MFA works normally) and consent to the scopes you need.

POWERSHELL
Install-Module Microsoft.Graph.Authentication, Microsoft.Graph.Users -Scope CurrentUser -Repository PSGallery

Connect-MgGraph -Scopes "User.Read.All"

# Confirm who you are signed in as and which scopes you hold
Get-MgContext | Select-Object Account, TenantId, Scopes

Get the service plans enabled for a user (the same example as the original post) using the SDK cmdlet:

POWERSHELL
$license = Get-MgUserLicenseDetail -UserId "[email protected]"
$license[0].ServicePlans | Select-Object ServicePlanName, ProvisioningStatus

Or call any Graph URL directly with Invoke-MgGraphRequest. This reuses the SDK's token, so you never touch the token yourself:

POWERSHELL
$result = Invoke-MgGraphRequest -Method GET -Uri "https://graph.microsoft.com/v1.0/users/[email protected]/licenseDetails"
$result.value[0].servicePlans

Option 2: App-Only Authentication with a Certificate

For scheduled tasks and Azure Automation, use application permissions with a certificate. There's no user, no password, and no MFA prompt.

  1. In your app registration, add Application permissions (for example User.Read.All) under API permissions and grant admin consent.
  2. Create and upload a certificate:
POWERSHELL
# Create a self-signed certificate in the current user's store (valid for 1 year)
$cert = New-SelfSignedCertificate -Subject "CN=LAB365-Graph-Automation" `
    -CertStoreLocation "Cert:\CurrentUser\My" -KeySpec Signature -KeyExportPolicy NonExportable `
    -NotAfter (Get-Date).AddYears(1)

# Export only the public key and upload it to the app registration under Certificates & secrets
Export-Certificate -Cert $cert -FilePath ".\LAB365-Graph-Automation.cer"
$cert.Thumbprint
  1. Connect with the certificate thumbprint:
POWERSHELL
$tenantId   = "yourtenant.onmicrosoft.com"
$appId      = "3046dee6-cc78-4f0d-8a16-d2e95fea5c10"
$thumbprint = "<CertificateThumbprint>"

Connect-MgGraph -TenantId $tenantId -ClientId $appId -CertificateThumbprint $thumbprint -NoWelcome

Get-MgUserLicenseDetail -UserId "[email protected]" | Select-Object -ExpandProperty ServicePlans
TIP:
In Azure Automation or on an Azure VM, skip certificates entirely and use a managed identity: Connect-MgGraph -Identity.

Option 3: Raw REST Token (Client Credentials, No Modules)

If you need the bearer token itself, for example to call Graph from a tool that has no Graph SDK, request it from the Microsoft identity platform v2.0 token endpoint. This example uses a client secret for simplicity. Use a certificate or managed identity in production.

POWERSHELL
$tenantId     = "yourtenant.onmicrosoft.com"
$appId        = "3046dee6-cc78-4f0d-8a16-d2e95fea5c10"
$clientSecret = Get-Secret -Name "LAB365-Graph-Secret" -AsPlainText   # SecretManagement module; never hard-code secrets

$tokenResponse = Invoke-RestMethod -Method POST `
    -Uri "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token" `
    -ContentType "application/x-www-form-urlencoded" `
    -Body @{
        client_id     = $appId
        client_secret = $clientSecret
        scope         = "https://graph.microsoft.com/.default"
        grant_type    = "client_credentials"
    }

$accessToken = $tokenResponse.access_token

$apiUrl  = "https://graph.microsoft.com/v1.0/users/[email protected]/licenseDetails"
$rawData = Invoke-RestMethod -Headers @{ Authorization = "Bearer $accessToken" } -Uri $apiUrl -Method GET
$rawData.value[0].servicePlans

The .default scope means "all application permissions already granted to this app". Tokens are valid for about 60–90 minutes, so long-running scripts must request a new one before it expires. Options 1 and 2 handle this automatically.


Next in the Series


Archival Reference: Original ADAL Method (Do Not Use)

Click to view the original 2019 ADAL / ROPC code

This code depended on the retired AzureAD module's ADAL assemblies and a plain-text password. It fails for MFA-enabled accounts and should not be used.

POWERSHELL
$AadModule = Import-Module -Name AzureAD -ErrorAction Stop -PassThru
$adal = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.dll"
$adalforms = Join-Path $AadModule.ModuleBase "Microsoft.IdentityModel.Clients.ActiveDirectory.Platform.dll"
[System.Reflection.Assembly]::LoadFrom($adal) | Out-Null
[System.Reflection.Assembly]::LoadFrom($adalforms) | Out-Null

$AppID = "3046dee6-cc78-4f0d-8a16-d2e95fea5c10"
$Username= "[email protected]"
$Password= "Password"
$resourceURI = "https://graph.microsoft.com"
$authority = "https://login.microsoftonline.com/common"
$AADCredential = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.UserPasswordCredential" -ArgumentList $Username,(ConvertTo-SecureString -AsPlainText $Password -Force)
$AuthContext = New-Object "Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContext" -ArgumentList $authority
$AuthResult = [Microsoft.IdentityModel.Clients.ActiveDirectory.AuthenticationContextIntegratedAuthExtensions]::AcquireTokenAsync($authContext, $resourceURI, $Appid, $AADCredential);
$accessToken = $authResult.result.AccessToken