Web requests can be made from Powershell with HTTP authentication in the following 2 ways:
1. Using credential objects
2. Adding appropriate header
A JSON request with a body can be made as follows:
1. Using credential objects
$username = "foo"
$password = "bar" | ConvertTo-SecureString -asPlainText -Force
$cred = New-Object System.Management.Automation.PSCredential($username,$password)
$res = Invoke-WebRequest http://localhost:3000 -Credential $cred
$res.Content
2. Adding appropriate header
$acctname = "foo"
$password = "bar"
$params = @{uri = 'http://localhost:3000';
Method = 'Get'; #(or POST, or whatever)
Headers = @{Authorization = 'Basic ' + [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes("$($acctname):$($password)"));
} #end headers hash table
} #end $params hash table
$var = curl @params
Curl
above is same as Invoke-WebRequest
because on Windows, by default curl
is just an alias to Invoke-WebRequest
. A JSON request with a body can be made as follows:
$res = Invoke-WebRequest http://localhost:3000/stores -Credential $cred -Method POST -Headers @{"Content-Type"="application/json"} -Body (ConvertTo-Json @{"Key"="Value"})