Search code examples
powershell-4.0

Invoke-RestMethod In Powershell Authorization Issue (header)


I am trying to do a basic GET with Invoke-RestMethod via PS to our Netbox environment. I am using my API token from netbox and putting it in an Authorization header, but regardless of how I try it, I get "Authentication credentials were not provided" from Powershell. I'm at a loss as this works perfectly fine via Postman.

$APIKey = "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" (removed)

$Headers = @{}
$Headers.Add("Authorization", "Token $APIKey") 
$Headers.Add("Content-Type", "application/json")
$Headers.Add("Accept", "application/json")

$URI = "https://dcim.xxxxxxx.net/api/dcim/devices"

$Test = Invoke-RestMethod -Uri $URI -Headers $Headers

I've had tried formatting the headers many different ways, hardcoding things just to test, but to no avail.


Solution

  • Turns out if was a combination of a redirect (301) on the Netbox nginx, and the fact that Postman was adding a trailing "/" to the URI without showing that on the request preview. Nginx was adding the "/" when it received it as a redirection and then stripping the header (As would be expected). I just had to add the trailing "/" and it was fine. (Sigh).