I'm having a bit of a struggle trying to get my authorization headers to work correctly when using Invoke-RestMethod to retrieve secrets from my Azure KeyVaults in PowerShell 5. The code runs perfectly in PowerShell 7, but I'm running into issues with the authorization in PowerShell 5. My working code in PowerShell 7 looks like this: I connect to my Azure account, grab the access token, and then use Invoke-RestMethod to get the secret. But when I try to translate that to PowerShell 5, I get an 'Unauthorized' error message. I've tried multiple header formats, but nothing seems to work. Any help would be greatly appreciated!
1 Answer
It looks like the issue might stem from the fact that `Get-AzAccessToken` returns a SecureString in PowerShell 5. You can convert it to plaintext before using it in your headers. Here's a snippet to try:
```powershell
$token = Get-AzAccessToken -ResourceUrl "https://vault.azure.net"
$header = @{
Authorization = "Bearer $(ConvertFrom-SecureString $token.token -AsPlainText)"
}
```
This change could help resolve the unauthorized error you're seeing!

Just a quick note: The `-AsPlainText` option is only available in PowerShell 7, so you'll need to convert the SecureString manually for PowerShell 5. I came across this:
```powershell
$bstr = [System.Runtime.InteropServices.Marshal]::SecureStringToBSTR($token)
$PlainToken = [System.Runtime.InteropServices.Marshal]::PtrToStringAuto($bstr)
[System.Runtime.InteropServices.Marshal]::ZeroFreeBSTR($bstr)
$headers = @{
Authorization = "Bearer $PlainToken"
}
```
This should help you get the correct format for your authorization header!