'AzureAD Powershell cmdlets work locally but erroring in Azure DevOps Microsoft Hosted Agent with "Error reading JToken from JsonReader"

I have a powershell script that runs locally on my Windows Desktop running powershell 7.2.1. However when run on a Microsoft Hosted Windows-Latest agent in Azure DevOps, it runs the all lines just fine (I get all tokens and can call Connect-AzureAD), but gives a very cryptic message on the last command.

##[error]Error reading JToken from JsonReader. Path '', line 0, position 0.
##[error]PowerShell exited with code '1'.

It looks like any command from the AzureAD module gives same error. I've tried adding -Debug and -Verbose but no extra info.

Install-Module -Name 'AzureAD' -Force -Scope CurrentUser -SkipPublisherCheck -AllowClobber 
Import-Module AzureAD
$currentAzureContext = Get-AzContext
$context = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile.DefaultContext;
$graphToken = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, $context.Environment, $context.Tenant.Id.ToString(), $null, [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never, $null, "https://graph.microsoft.com").AccessToken
$aadToken = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, $context.Environment, $context.Tenant.Id.ToString(), $null, [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never, $null, "https://graph.windows.net").AccessToken

Connect-AzureAD -AadAccessToken $aadToken -AccountId $context.Account.Id -TenantId $context.tenant.id -MsAccessToken $graphToken

Get-AzureADGroupAppRoleAssignment -ObjectId 00000000-0000-0000-0000-000000000000 #all ok up to line before this one, but this one fails with Error reading JToken (and only in Azure DevOps, not on my local)

Some more debugging info

Printing version info [helpful to compare against what you might be running locally when debugging]

Key   : PSVersion
Value : 7.2.1
Name  : PSVersion


Key   : PSEdition
Value : Core
Name  : PSEdition


Key   : GitCommitId
Value : 7.2.1
Name  : GitCommitId


Key   : OS
Value : Microsoft Windows 10.0.19043
Name  : OS


Key   : Platform
Value : Win32NT
Name  : Platform


Key   : PSCompatibleVersions
Value : {1.0, 2.0, 3.0, 4.0…}
Name  : PSCompatibleVersions


Key   : PSRemotingProtocolVersion
Value : 2.3
Name  : PSRemotingProtocolVersion


Key   : SerializationVersion
Value : 1.1.0.1
Name  : SerializationVersion


Key   : WSManStackVersion
Value : 3.0
Name  : WSManStackVersion

Get-PSRepository

Name                      : PSGallery
SourceLocation            : https://www.powershellgallery.com/api/v2
Trusted                   : False
Registered                : True
InstallationPolicy        : Untrusted
PackageManagementProvider : NuGet
PublishLocation           : https://www.powershellgallery.com/api/v2/package/
ScriptSourceLocation      : https://www.powershellgallery.com/api/v2/items/psscript
ScriptPublishLocation     : https://www.powershellgallery.com/api/v2/package/
ProviderOptions           : {}


Solution 1:[1]

##[error]Error reading JToken from JsonReader. Path '', line 0, position 0.

The Error shows that mostly an unformatted JSON. So, try to avoid this by using the below workaround.

Instead of directly giving the ObjectID you can get the Object ID using Get-AzureADGroup and assign it to some variable and use it in a Get-AzureADGroupAppRoleAssignment -ObjectId. Which follows

$GroupId = (Get-AzureADGroup -Top 1).ObjectId
Get-AzureADGroupAppRoleAssignment -ObjectId $GroupId

Refer here

Updated Answer

Instead of using the AzureAD. Try to use the AzureADPreview latest Module.

# use this in your pipeline to fix the issue
Install-Module AzureADPreview 

Import-Module AzureADPreview 

Solution 2:[2]

Try setting pwsh:false on Devops Powershell task. It fixed the issue that i had connecting Azure AD on Devops.

- task: AzurePowerShell@5
  displayName:{Displayname}
  inputs:
    azureSubscription: {serviceConnectionPrd}
    ScriptType: InlineScript
    Inline: |
      Install-Module -Name 'AzureAD' -Force -Scope CurrentUser -SkipPublisherCheck -AllowClobber 
      Import-Module AzureAD
      $currentAzureContext = Get-AzContext
      $context = [Microsoft.Azure.Commands.Common.Authentication.Abstractions.AzureRmProfileProvider]::Instance.Profile.DefaultContext;
      $graphToken = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, $context.Environment, $context.Tenant.Id.ToString(), $null, [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never, $null, "https://graph.microsoft.com").AccessToken
      $aadToken = [Microsoft.Azure.Commands.Common.Authentication.AzureSession]::Instance.AuthenticationFactory.Authenticate($context.Account, $context.Environment, $context.Tenant.Id.ToString(), $null, [Microsoft.Azure.Commands.Common.Authentication.ShowDialog]::Never, $null, "https://graph.windows.net").AccessToken
        
       Connect-AzureAD -AadAccessToken $aadToken -AccountId $context.Account.Id -TenantId $context.tenant.id -MsAccessToken $graphToken
        
       Get-AzureADGroupAppRoleAssignment -ObjectId 00000000-0000-0000-0000-000000000000 
        
   FailOnStandardError: true
   azurePowerShellVersion: LatestVersion
   pwsh: flase

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Pradeep kumar