2

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.

1 Answer 1

4

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. :)

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the feedback. I'm getting the same issue with your snippet where the $authorizationInfo variable has a different Base64String than Postman (your value is the same value as my code) so it's not working. Since this value is "wrong" I'm getting an "The supplied credentials are invalid." message
Looks like you were right, this will be an adventure. It works fine, I just learned that the credential username is case sensitive!!
Every API seems to have its own quirks, and I wish there was a nice "lots of things to try" doc I could send you. Occasionally I get lucky and some new API just works, but usually there is a head-meets-wall session for a while. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.