After updating PowerCLI to version 13.1, which has been released in April 2023, a couple of scripts that are using the Session Token provided by Connect-CIServer fail to work with the following error:
Invoke-WebRequest: {"minorErrorCode":"NOT_AUTHENTICATED","message":"[] This operation is denied.","stackTrace":null}
According to the official announcement, there have been changes to the authentication mechanism of Connect-CIServer. This change does not affect any functions that come with PowerCLI, but many community functions and scripts that include custom API calls.
In previous versions, you could simply snatch the authentication token that is stored in the $global:DefaultCIServers.SessionId global variable and use with an x-vcloud-authorization header in your custom API calls. Since PowerCLI 13.1, you now get a Bearer Token as SessionId/SessionSecret.
Making API calls with the Bearer Token is as easy as in previous versions. You just have to add it as "Authorization" header, instead of "x-vcloud-authorization".
Here is an example that uses the Bearer Token to make a rest call that lists all Edge Gateways:
Connect-CIServer vcloud.virten.lab -User Administrator $headers = @{ "Authorization" = $Global:DefaultCIServers.SessionID } $headers.Add("Accept", 'application/json;version=35.0') Invoke-WebRequest -Uri "https://vcloud.virten.lab/cloudapi/1.0.0/edgeGateways/" -Headers $headers
To make scripts compatible with old and new PowerCLI versions, I created the Get-AuthHeader helper function that creates the correct header for all PowerCLI versions. It is intended to be used as follows:
$headers = Get-AuthHeader $Server $headers.Add("Accept", 'application/json;version=35.0')
The helper function is available in my GitHub: /virten-scripts/powershell/vcd_helper_functions.ps1