Connecting to Microsoft Graph using Powershell 7.2 in Automation Runbook

Anonymous
2025-07-13T05:06:21+00:00

Hi experts,

I need some assistance with connecting to Microsoft graph and delete users in a security group who are created in past 5 days.

I created a runtime environment with PowerShell 7.2 and added packages, Microsoft.Graph.Users, Groups, Authentication.

I added this code to a new runbook and using SPN for authentication. All required permissions to read and delete users are available with admin consent for the Graph using SPN.

I declared variables in automation runbook for SPN related.

Code is here:

$Client_Id = Get-AutomationVariable -Name Client_Id $Client_Secret = Get-AutomationVariable -Name Client_Secret$Tenant_Id = Get-AutomationVariable -Name Tenant_Id

Write-output "Fetched authentication details successfully"

#Convert the Client Secret to a Secure String

$SecureClientSecret = ConvertTo-SecureString -String $Client_Secret -AsPlainText -Force $ClientSecretCredential = [System.Management.Automation.PSCredential]::new($Client_Id, $SecureClientSecret)

# Connect to Microsoft Graph Using the Tenant ID and Client Secret CredentialConnect-MgGraph -TenantId $Tenant_Id -ClientSecretCredential $ClientSecretCredential

Get-MgUser -Top 1

When I ran the test/Run, I am facing the below error, can you please suggest me how to fix the error.

error: Invalid JWT access token

3 permissions assigned to SPN /App Id

Microsoft 365 and Office | Subscription, account, billing | For education | Other

Locked Question. This question was migrated from the Microsoft Support Community. You can vote on whether it's helpful, but you can't add comments or replies or follow the question.

0 comments No comments
{count} votes

5 answers

Sort by: Most helpful
  1. Anonymous
    2025-07-13T06:25:10+00:00

    Dear pemmasaniphaneendra pavan sai,

    Welcome to community!

    Thanks for sharing your PowerShell 7.2 runbook setup for connecting to Microsoft Graph using a service principal (SPN). Based on the error you're encountering "Invalid JWT access token" and according to my research, here are some explanations and recommended fix.

    This is a known compatibility problem betweenbPowerShell 7.2 runtime in Azure Automation and Microsoft.Graph PowerShell modules version 2.26.1 or later. These versions introduce changes in how JWT tokens are handled, which causes the Connect-MgGraph command to fail with the "Invalid JWT access token" error, even when credentials and permissions are correctly configured.

    Option 1: Downgrade Microsoft.Graph Modules to Version 2.25.0

    I have one Azure Automation account where Microsoft Graph modules installed with 2.26.1 version:

    Image

    When I ran your script in PowerShell 7.2 runbook, I too got same error as below:

    Image

    To resolve this, you need to revert back its previous version 2.25.0 as a workaround.

    In my case, I deleted the existing 2.26.1 Microsoft Graph modules as below:

    Image

    Now, I ran below PowerShell script in Azure Cloud Shell to install2.25.0version Microsoft Graph modules:

    Import Microsoft.Graph.Authentication module

    $moduleName = 'Microsoft.Graph.Authentication'

    $moduleVersion = '2.25.0'

    New-AzAutomationModule -AutomationAccountName 'AutAccName' -ResourceGroupName 'rgName' -Name $moduleName -ContentLinkUri "https://www.powershellgallery.com/api/v2/package/$moduleName/$moduleVersion" -RuntimeVersion '7.2'

    Import Microsoft.Graph.Users module

    $moduleName = 'Microsoft.Graph.Users'

    $moduleVersion = '2.25.0'

    New-AzAutomationModule -AutomationAccountName 'AutAccName' -ResourceGroupName 'rgName' -Name $moduleName -ContentLinkUri "https://www.powershellgallery.com/api/v2/package/$moduleName/$moduleVersion" -RuntimeVersion '7.2'

    Response:

    Image

    Make sure to wait for few minutes until the modules status turns "Available" as below:

    Image

    When I ran the PowerShell script again after reverting back to2.25.0version, I got the response successfully as below:

    Define App Registration details

    $tenantId = "tenantId" $clientId = "appId"

    $clientSecret = "secret" # Client secret value

    Define the resource for Azure Management API

    $scope = "https://graph.microsoft.com/.default"

    $tokenUrl = "https://login.microsoftonline.com/$tenantId/oauth2/v2.0/token"

    Get authentication token using client credentials flow

    $body = @{

    grant_type = "client_credentials"

    client_id = $clientId

    client_secret = $clientSecret

    scope = $scope

    }

    try {

    $response = Invoke-RestMethod -Method Post -Uri $tokenUrl -ContentType "application/x-www-form-urlencoded" -Body $body

    $accessToken = $response.access_token

    Validate token retrieval

    if (-not $accessToken) {

    Write-Host "Failed to obtain access token" -ForegroundColor Red

    exit

    }

    Write-Host "Access Token obtained successfully" -ForegroundColor Green

    Convert the access token to a SecureString

    $secureAccessToken = ConvertTo-SecureString $accessToken -AsPlainText -Force

    Connect to Microsoft Graph using the SecureString access token

    Connect-MgGraph -AccessToken $secureAccessToken

    Write-Host "Connected to Microsoft Graph successfully" -ForegroundColor Green

    }

    catch {

    Write-Host "Error: $_" -ForegroundColor Red

    }

    Import-Module Microsoft.Graph.Users

    Get-MgUser -Top 10 | Select-Object DisplayName, Id

    Response:

    Image

    To know more regarding this known issue, here are my reference: Invalid JWT access token - Microsoft Q&A

    Additional Tips

    • Ensure your SPN has the correct permissions (e.g., User.Read.All, Group.ReadWrite.All) with admin consent.
    • If using ClientSecretCredential, make sure you're not passing a SecureString directly—this is a common mistake. Instead, use Connect-MgGraph -ClientId -TenantId -ClientSecret directly or use Invoke-RestMethod to fetch the token manually if needed

    I hope this information is helpful. Please follow these steps and let me know the outcome.       

    ***Note:***Please understand that our initial response does not always resolve the issue immediately. However, with your help and more detailed information, we can work together to find a solution. 

    If you have any difficulties when trying these methods or the issue still persists after completing the above, feel free to reach out, and we can further investigate the problem together.           

    Thanks for your patience and understanding so far.  Looking forward to hearing from you.         

    Best Regards,          

    Vivian - MSFT | Microsoft Community Support Specialist


    *If my answer is helpful,please mark it as an answer, which*****will definitely help other community members with similar questions find a solution to their problem faster.

    2 people found this answer helpful.
    0 comments No comments
  2. Deleted

    This answer has been deleted due to a violation of our Code of Conduct. The answer was manually reported or identified through automated detection before action was taken. Please refer to our Code of Conduct for more information.


    Comments have been turned off. Learn more

  3. Anonymous
    2025-07-15T06:01:02+00:00

    Hello pemmasaniphaneendra pavan sai, 

    Just following up to see how things are going, your updates would be greatly appreciated! If you have any difficulties, please do not hesitate to contact us.

    Looking forward to hearing from you. 
    Best regards, 

    Vivian - MSFT | Microsoft Community Support Specialist

    1 person found this answer helpful.
    0 comments No comments
  4. Anonymous
    2025-07-19T07:58:02+00:00

    Thanks Vivian-H for the detailed explanation. I need to do this with the approach you mentioned.

    I tried to check on how to mark this response as an answer but unable to find it. If you have the permissions to mark it, go ahead.

    0 comments No comments
  5. Anonymous
    2025-07-20T23:54:22+00:00

    Good day, pemmasaniphaneendra pavan sai!

    I hope you are doing well.  

    Regarding your thread Connecting to Microsoft Graph using Powershell 7.2 in Automation - Microsoft Community. We are glad that helps. Meanwhile, hope you kindly mark it as an answer and vote it up by your original account which raised this question (as seen in the screenshot).

    Once marked, it will automatically pin to top. As other users will also search information in this community, your valuable marked answer will definitely also help other users who have similar queries easily to find the correct channel and useful information more quickly.  

    Greatly Appreciate again for your patience and understanding.  

    Looking forward to hearing from you.         

    Best Regards,          

    Vivian - MSFT | Microsoft Community Support Specialist

    0 comments No comments