Friday, 7 October 2016

Web request with HTTP authentication from Powershell

Web requests can be made from Powershell with HTTP authentication in the following 2 ways:

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

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"})

No comments: