Authentication Flows: Azure Automation Account

Obtaining an Access Token for Microsoft Graph from an Azure Automation Account Runbook using a system-assigned Managed Identity.

PowerShell

function Get-ManagedIdentityMsGraphAccessToken {
    [CmdletBinding()]
    [OutputType([string])]
    param()
    process {
        $headers = [System.Collections.Generic.Dictionary[string, string]]::new()
        $headers.Add("X-IDENTITY-HEADER", $env:IDENTITY_HEADER) 
        $headers.Add("Metadata", "True") 

        $body = @{resource = 'https://graph.microsoft.com/' } 
        $params = @{
            Uri         = $env:IDENTITY_ENDPOINT;
            Method      = 'POST';
            Headers     = $headers;
            ContentType = 'application/x-www-form-urlencoded';
            Body        = $body;
        }
        $graphAccessToken = Invoke-RestMethod @params
        $graphAccessToken.access_token
    }
}
$accessToken = Get-ManagedIdentityMsGraphAccessToken
# Connect-MgGraph -AccessToken $accessToken