PowerShell's Invoke-RestMethod equivalent of curl -u (Basic Authentication)

Borek Bernard picture Borek Bernard · Jul 10, 2014 · Viewed 75.9k times · Source

What is the equivalent of

curl -u username:password ...

in PowerShell's Invoke-RestMethod? I tried this:

$securePwd = ConvertTo-SecureString "password" -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential ($username, $securePwd)

Invoke-RestMethod -Credential $credential ...

but it returns 401, Unauthorized.

Answer

Borek Bernard picture Borek Bernard · Jul 10, 2014

This is the only method that worked for me so far:

$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $username,$password)))

Invoke-RestMethod -Headers @{Authorization=("Basic {0}" -f $base64AuthInfo)} ...

But I don't believe there isn't a better way.