Authenticate Connect-MgGraph using OIDC in GitHub Actions

Azure sky with pink cloud. Connecting to "Azure" afterall.
Photo by Martin Adams / Unsplash

I'm running a number of maintenance scripts against our Azure EntraId to manage GitHub related things. Removing dormant users, asking users to setup their notification email correctly etc.

For a long time, I ran these scripts with an interactive session, before moving them over to GitHub Actions. Recently I made the move to convert my scripts to a workflow and changed the authentication mechanism to OIDC-connect, in order to remove the need to manage secrets and tokens.

The documentation is quite clear on how to set things up:

Authenticate to Azure from GitHub Actions by OpenID Connect
Securely authenticate to Azure services from GitHub Actions workflows using Azure Login action with OpenID Connect (OIDC).

Unfortunately, while it explains how to setup an Azure PowerShell session using enable-AzPSSession: true, it doesn't explain how to authenticate using connect-mggraph.

After some experimentation (and of course some help from GitHub Copilot), I figured out I could query the access token from az, then pass that straight to connect-mggraph. So now my workflow looks like this:

- name: Azure CLI Login
  uses: azure/login@v2
    with:
      client-id: ${{ secrets.AZURE_CLIENT_ID }}
      tenant-id: ${{ secrets.AZURE_TENANT_ID }}
      allow-no-subscriptions: true
      
  - name: Assign Costcenters
    run: |
       $accessToken = az account get-access-token --resource https://graph.microsoft.com `
         --query accessToken --output tsv
       write-host "::add-mask::$accessToken"
       $accessToken = $accessToken | ConvertTo-SecureString -AsPlainText -Force
       Connect-MgGraph -AccessToken $accessToken -NoWelcome

       # rest of the script here ... 
    shell: pwsh 

And my scripts can happily query the Microsoft Graph.