Powershell Invoke-Restmethod Authorization header issue

92 Views Asked by At

I am trying to query the endpoint for target failures in zendesk: https://developer.zendesk.com/api-reference/ticketing/targets/target_failures/

Specifically: List Target Failures GET /api/v2/target_failures Returns the 25 most recent target failures, per target.

I am passing a username and password into:

$username
$password

Here is how I am constructing the request:

$params = @{
    Uri = "https://subdomain.zendesk.com/api/v2/target_failures";
    Method = 'Get';
    Headers = @{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username,$password))); Accept = "application/json";
    } #end headers hash table
} #end $params hash table
Invoke-RestMethod @params 

I am getting this error:

Invoke-RestMethod : {"error":"Couldn't authenticate you"}
At line:1 char:1
+ Invoke-RestMethod @params
+ ~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebExc
   eption
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

Edit: Finally got this working via the following method:

Connect-AzAccount
Set-AzContext "SUBSCRIPTION"
$user = Get-AzKeyVaultSecret -VaultName 'KEYVAULT' -Name 'SECRET' -asplaintext
$pass = Get-AzKeyVaultSecret -VaultName 'KEYVAULT' -Name 'SECRET' -asplaintext
$pair = "${user}:${pass}"
$bytes = [System.Text.Encoding]::ASCII.GetBytes($pair)
$base64 = [System.Convert]::ToBase64String($bytes)
$basicAuthValue = "Basic $base64"
$headers = @{ Authorization = $basicAuthValue ; Accept = "application/json"}
Invoke-WebRequest -uri "https://SUBDOMAIN.zendesk.com/api/v2/target_failures" -Headers $headers

Not 100% sure why this worked and my original script did not, but if someone could explain it to me that would be super helpful.

0

There are 0 best solutions below