greatname
greatname

Reputation: 23

REST-API Basic Authentication and Invoke-WebRequest via Powershell

Trying to connect to a REST-API via Powershell client. When testing the endpoint in Postman, I have no problems at all. Here's the main part of the function (I have a [pscredential]$Creds parameter that I use to get the username and password):

[string]$username = $Creds.UserName
[string]$password = (New-Object System.Net.NetworkCredential($Creds.UserName, $Creds.Password, 'Null')).Password
[string]$authorizationInfo= ([Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(('{0}:{1}' -f $username, $password))))

Invoke-WebRequest -Uri "https://$($HostName)/api/" -Method Get -Headers @{Authorization = ('Basic {0}' -f $authorizationInfo)}

For some reason the Authorization header is different in my script than in Postman. I can even copy the Authorization header out of Postman and paste it into the -Headers parameter and everything works fine. I just don't see where I'm getting this wrong.

Upvotes: 2

Views: 23231

Answers (1)

adamt8
adamt8

Reputation: 357

I can't tell you why that's not working, but I can suggest something that works for me all the time with APIs:

$auth = $username + ':' + $upassword
$Encoded = [System.Text.Encoding]::UTF8.GetBytes($auth)
$authorizationInfo = [System.Convert]::ToBase64String($Encoded)
$headers = @{"Authorization"="Basic $($authorizationInfo)"}

Invoke-WebRequest -Uri "https://$($HostName)/api/" -Method GET -Headers $headers

If that doesn't work, try this subtle difference with Invoke-Restmethod:

Invoke-RestMethod -Uri "https://$($HostName)/api/" -Method GET -Headers $headers

Working with APIs is always an adventure. Keep trying. :)

Upvotes: 4

Related Questions