Category Archives: Powershell

Easily get access token for Azure Management API

Wrote this little snippet that assumes a logged in session (Connect-AzAccount) and easily/quickly produces an auth header.

function get-azRMAccessHeader(){
    $profile = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile
    $context = Get-AzContext
    $client = New-Object Microsoft.Azure.Commands.ResourceManager.Common.RMProfileClient($profile)

    $header = @{
        "Authorization" = "Bearer $($client.AcquireAccessToken((Get-AzContext).Tenant.TenantId).AccessToken)"
    return $header

Powershell Cert based authentication against the Graph API using a certificate from Keyvault

In automation scenarios it is common to use a service principal (app based) to work with the Graph API, or in my example, with PNP PowerShell against SharePoint (but both scenario’s work the same).

First, you’d need a client certificate, e.g. like this:

$folder = "c:\users\JosLieben\Desktop"
$cert=New-SelfSignedCertificate -Subject "CN=JOS" -CertStoreLocation "Cert:\CurrentUser\My"  -KeyExportPolicy Exportable -KeySpec Signature -HashAlgorithm "SHA256" -Provider "Microsoft Enhanced RSA and AES Cryptographic Provider"
Export-Certificate -Cert $cert -FilePath "$folder\jos.cer" 
Export-PfxCertificate -Password (ConvertTo-SecureString $clientCertPwd -AsPlainText -Force) -Cert $cert -FilePath "$folder\jos.pfx"

You’d then upload the .cer file as a certificate on your service principal to let Azure AD recognize your cert as a valid ‘password’ for your app registration.

Next you’d upload your .pfx file into Keyvault.

Finally, you can use Powershell to construct an access token for a given scope:

$tenantId = "YOURTENANTID"
$clientId = "YOURCLIENTID"
$scope = "" #or, e.g. https://$($tenantName) openid profile offline_access
$secret = Get-AzKeyVaultSecret -VaultName "YOURKEYVAULTNAME" -Name cippCert -AsPlainText
$clientCert = New-Object System.Security.Cryptography.X509Certificates.X509Certificate2 -ArgumentList @([Convert]::FromBase64String($secret),"",[System.Security.Cryptography.X509Certificates.X509KeyStorageFlags]::Exportable)

$header = @{
    alg = "RS256"
    typ = "JWT"
    x5t = [System.Convert]::ToBase64String(($clientCert.GetCertHash()))
} | ConvertTo-Json -Compress

$claimsPayload = @{
    aud = "$tenantId/oauth2/token"
    exp = [math]::Round(((New-TimeSpan -Start ((Get-Date "1970-01-01T00:00:00Z" ).ToUniversalTime()) -End (Get-Date).ToUniversalTime().AddMinutes(2)).TotalSeconds),0)
    iss = $clientId
    jti = (New-Guid).Guid
    nbf = [math]::Round(((New-TimeSpan -Start ((Get-Date "1970-01-01T00:00:00Z" ).ToUniversalTime()) -End ((Get-Date).ToUniversalTime())).TotalSeconds),0)
    sub = $clientId
} | ConvertTo-Json -Compress

$headerjsonbase64 = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($header)).Split('=')[0].Replace('+', '-').Replace('/', '_')
$claimsPayloadjsonbase64 = [Convert]::ToBase64String([System.Text.Encoding]::UTF8.GetBytes($claimsPayload)).Split('=')[0].Replace('+', '-').Replace('/', '_')

$preJwt = $headerjsonbase64 + "." + $claimsPayloadjsonbase64
$toSign = [System.Text.Encoding]::UTF8.GetBytes($preJwt)
$privateKey = $clientCert.PrivateKey
$alg = [Security.Cryptography.HashAlgorithmName]::SHA256
$padding = [Security.Cryptography.RSASignaturePadding]::Pkcs1
$signature = [Convert]::ToBase64String($privateKey.SignData($toSign,$alg,$padding)) -replace '\+','-' -replace '/','_' -replace '='

$jwt = $headerjsonbase64 + "." + $claimsPayloadjsonbase64 + "." + $signature

$Authbody = @{
    'tenant' = $tenantId
    'scope' = $scope
    'client_assertion_type' = 'urn:ietf:params:oauth:client-assertion-type:jwt-bearer'
    'client_id'     = $clientId
    'grant_type'    = 'client_credentials'
    'client_assertion' = $jwt

$accessToken = (Invoke-RestMethod -Method post -Uri "$($tenantid)/oauth2/v2.0/token" -Body $Authbody -ErrorAction Stop).accesstoken

The token can then be used to used to call Graph. And an example that shows how to use a sharepoint scoped token for the Sharepoint PNP PowerShell moddule:

#use scope: https://$($tenantName)

connect-PnPOnline -Url "https://$($tenantName)" -AccessToken $accessToken -ReturnConnection

The mysterious X-MS-Forest header

When working with the API, I noticed that the MS portal uses an X-MS-Forest header.

At first, ignoring this went fine as doing GET calls to this api didn’t seem to require it. But, of course the moment I wanted more, it suddenly WAS required (PUT/POST).

The question was; how does the portal determine the value for this header and how do we replicate that? Well, that wasn’t difficult: apparently a call to suffices and returns the value for the X-MS-Forest header for the tenant identified in your token. Example:

    $headers = Get-GraphToken -tenantid $tenantId -scope ""
    #get the correct forest
    $tenantInfo = Invoke-RestMethod -Method GET -uri "" -UseBasicParsing -ContentType "application/json" -Headers $headers
    #add the X-MS-Forest header (required) for subsequent calls
    $headers["X-MS-Forest"] = $tenantInfo.serviceDiscovery.Headers.'X-MS-Forest'

Local client SPO migration script

For a customer case/project, we wanted to move only recently synced/modified Sharepoint Online data from Tenant A to the user’s Desktop on the device itself.

The Desktop was synced to Onedrive for Business in Tenant B.

After copying, files from Tenant A should become read-only on the local device, and the link in Explorer to Tenant A’s sharepoint should be removed, including the actual onedrive sync relationship to prevent further ul/dl’s.

Resulting in