Skip to content

InvalidAuthenticationToken Error at Invoke-RestMethod - Partial Solution provided #50

Description

@jkbryan

Describe the bug
InvalidAuthenticationToken Error at Invoke-RestMethod - Partial Solution provided

Add error message
Invoke-RestMethod : {"error":{"code":"InvalidAuthenticationToken","message":"The 'EvolvedSecurityTokenService' access token is invalid."}}
At line:8 char:1

  • Invoke-RestMethod -Method Get -Uri $uri -Headers $headers
  •   + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
      + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand
    
    
    

To Reproduce
Perform interactive login with Login-AzAccount, then try to run:

.\src\New-LogicAppDoc.ps1 -SubscriptionId -ResourceGroupName -LogicAppName

If possible upload the Logic App Flow or Power Automate Flow code.

Expected behavior
When I used this script last year, the script ran fine and output the markdown file.

Screenshots
N/A

PowerShell version:
5 (using PowerShell ISE) and 7 (using VS Code) tried:
Name Value


PSVersion 5.1.26100.4768
PSEdition Desktop
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...}
BuildVersion 10.0.26100.4768
CLRVersion 4.0.30319.42000
WSManStackVersion 3.0
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1

Name Value


PSVersion 7.5.2
PSEdition Core
GitCommitId 7.5.2
OS Microsoft Windows 10.0.26100
Platform Win32NT
PSCompatibleVersions {1.0, 2.0, 3.0, 4.0…}
PSRemotingProtocolVersion 2.3
SerializationVersion 1.1.0.1
WSManStackVersion 3.0

LogicAppDocs version
Current

Additional context
I spent some time debugging this issue:
Logged in account does have valid permissions - verified via AZ CLI/ Azure RBAC role checks etc.
Ensured that my session was logged out from "other" tenants/ subscriptions.
Ensured that my session was re-logged into the proper subscription and Entra tenant using "Connect-AzAccount -Subscription '' -Tenant '' -DeviceCode".
Tried using "api-version=2019-05-01".
Inspected token to validate audience etc.

Tested the Invoke-RestMethod snip, with the same result (note that the resource URL is changed):

$token = Get-AzAccessToken -ResourceUrl "https://management.azure.com/"
$headers = @{
Authorization = "Bearer $($token.Token)"
"Content-Type" = "application/json"
}

$uri = "https://management.azure.com/subscriptions//resourceGroups//providers/Microsoft.Logic/workflows/?api-version=2019-05-01"
Invoke-RestMethod -Method Get -Uri $uri -Headers $headers

Summary, something in PowerShell (perhaps the Azure PowerShell app) is the source of the issue.

The workaround (tested in New-LogicAppDoc.ps1) - Use an App Registration to authenticate:

What changes?
Test-AzLogin function is removed - not required
Added the additional parameters for the service principal.
To run the new version:
.\New-LogicAppDoc.ps1 -SubscriptionId '' -ResourceGroupName '' -LogicAppName '' -OutputPath '' -tenantId '' -appId '' -secret ''
Ensure that your App Registration has permission to read the resource(s).

Replace lines 1 through to 137 with this code:

[CmdletBinding(DefaultParameterSetName = 'Azure')]
Param(
[Parameter(Mandatory = $true,
ParameterSetName = 'Azure')]
[string]$SubscriptionId,

[Parameter(Mandatory = $true)]
[string]$ResourceGroupName,

[Parameter(Mandatory = $true,
    ParameterSetName = 'Local')]
[string]$SubscriptionName,

[Parameter(Mandatory = $true,
    ParameterSetName = 'Local')]
[string]$Location,

[Parameter(Mandatory = $true,
    ParameterSetName = 'Local')]
[string]$FilePath,

[Parameter(Mandatory = $true)]
[string]$LogicAppName,

[Parameter(Mandatory = $true)]
[string]$tenantId,

[Parameter(Mandatory = $true)]
[string]$appId,

[Parameter(Mandatory = $true)]
[string]$secret,

[Parameter(Mandatory = $false)]
[string]$OutputPath = (Get-Location).Path,

[Parameter(Mandatory = $false)]
[boolean]$ConvertToADOMarkdown = $false,

[Parameter(Mandatory = $false)]
[bool]$Show = $false

)

Set-StrictMode -Version 3.0
$ErrorActionPreference = 'Stop'
$WarningPreference = 'SilentlyContinue'

@"
██╗ ██████╗ ██████╗ ██╗ ██████╗ █████╗ ██████╗ ██████╗ ██████╗ ██████╗ ██████╗███████╗
██║ ██╔���██╗██╔����� ██║██╔�����██╔��██╗██╔��██╗██╔��██╗██╔��██╗██╔���██╗██╔�����██╔�����
██║ ██║ ██║██║ ███╗██║██║ ███████║██████╔�██████╔�██║ ██║██║ ██║██║ ███████╗
██║ ██║ ██║██║ ██║██║██║ ██╔��██║██╔���� ██╔���� ██║ ██║██║ ██║██║ ╚����██║
███████╗╚██████╔�╚██████╔�██║╚██████╗██║ ██║██║ ██║ ██████╔�╚██████╔�╚██████╗███████║
╚������� ╚������ ╚������ ╚�� ╚������╚�� ╚��╚�� ╚�� ╚������ ╚������ ╚������╚�������

Author: Stefan Stranger
Github: https://github.com/stefanstranger/logicappdocs
Version: 1.1.5

"@.foreach({
Write-Host $_ -ForegroundColor Magenta
})

#region Import PowerShell Modules. Add more modules if needed
if (Get-Module -ListAvailable -Name PSDocs) {
Write-Verbose -Message 'PowerShell Module PSDocs is already installed'
}
else {
Write-Verbose 'Installing PowerShell Module PSDocs'
Install-Module PSDocs -RequiredVersion 0.9.0 -Scope CurrentUser -Repository PSGallery -SkipPublisherCheck -Confirm:$false -Force | Out-Null
}
#endregion

#region dot source Helper Functions
. (Join-Path $PSScriptRoot 'Helper.ps1')
#endregion

#region Set Variables
$templateName = 'Azure-LogicApp-Documentation'
$templatePath = (Join-Path $PSScriptRoot 'LogicApp.Doc.ps1')
#endregion

#region Get Logic App Workflow code
if (!($FilePath)) {

$SubscriptionName = (Get-AzContext).Subscription.Name    

Write-Host ('Getting Logic App Workflow code for Logic App "{0}" in Resource Group "{1}" and Subscription "{2}"' -f $LogicAppName, $ResourceGroupName, $(Get-AzContext).Subscription.Name) -ForegroundColor Green

$body = @{
  grant_type    = "client_credentials"
  client_id     = $appId
  client_secret = $secret
  resource      = "https://management.azure.com/"
}

$response = Invoke-RestMethod -Method Post -Uri "https://login.microsoftonline.com/$tenantId/oauth2/token" -Body $body
$token = $response.access_token

$headers = @{
  Authorization = "Bearer $token"
  "Content-Type" = "application/json"
}
$apiVersion = "2019-05-01"
$uri = "https://management.azure.com/subscriptions/$($subscriptionId)/resourceGroups/$($resourceGroupName)/providers/Microsoft.Logic/workflows/$($logicAppName)?api-version=$($apiVersion)"

$LogicApp = Invoke-RestMethod -Method Get -Uri $uri -Headers $headers
#endregion

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions