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

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.


I'm not sure why the -Credential parameter isn't working in your case, but it works with the httpbin service.

You can try this:

$pwd = ConvertTo-SecureString "MyPassword" -AsPlainText -Force
$cred = New-Object Management.Automation.PSCredential ('PsUser', $pwd)

Invoke-RestMethod 'http://httpbin.org/basic-auth/PsUser/MyPassword' -cred $cred

Edit: As noted in the comments, this method will not send the Authorization header on the initial request. It waits for a challenge response then re-sends the request with the Authorization header. This will not work for services that require credentials on the initial request.


It appears you should combine methods when they fail independently.

Create the credential and add it to the request.

Create the header and add it to the request.

$username = "username";
$password = ConvertTo-SecureString –String "password" –AsPlainText -Force
$credential = New-Object –TypeName "System.Management.Automation.PSCredential" –ArgumentList $username, $password

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

$getProjectUri = "yourUri"
Invoke-RestMethod -Method Get -Uri $getProjectUri -Headers @{Authorization = "Basic $base64AuthInfo" } -Credential $credential -ContentType "application/json"