Reputation: 323
While invoking an Invoke-RestMethod
using Powershell like:
Invoke-RestMethod -Method Get -Uri "https://google.com/api/GetData" -Headers $headers
and $headers
being
$headers = @{
Authorization="Secret $username $password"
Content='application/json'
}
What is the format expected for the parameters $username
and $password
?
Upvotes: 26
Views: 109861
Reputation: 2952
In my scenario, I used username
and password
in the body of the REST API call.
My body is:
$body = [PSCustomObject] @{
username=$Credential.UserName;
password=$Credential.GetNetworkCredential().Password;
} | ConvertTo-Json
In the function I use the PSCredential class:
[System.Management.Automation.PSCredential]
[System.Management.Automation.Credential()]
$Credential = [System.Management.Automation.PSCredential]::Empty,
Eventually, I call it this:
Invoke-RestMethod -Method Get -Uri "https://google.com/api/GetData" -ContentType application/json -Body $body
The ContentType
is set, because I expect JSON in response.
Upvotes: 1
Reputation: 1276
Solution provide by Rufer7 is right. I just want to add one more thing you can also pass the content parameter in Invoke-WebRequest method keeping the header more simple like this and getting the output in Json format. So my refined script will look like this.
Powershell Script:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
$headers = @{
Authorization="Bearer $token"
}
$responseData = (Invoke-WebRequest -Uri $Url -Method Get -Headers $headers -UseBasicParsing -ContentType "application/json").Content | ConvertFrom-Json | ConvertTo-Json
First line is optional only if you observe this error otherwise you can ignore this.
"Invoke-WebRequest : The request was aborted: Could not create SSL/TLS secure channel."
Upvotes: 12
Reputation: 4109
As far as I know you have to send a OAuth2 token in the request headers.
$headers = @{
Authorization="Bearer $token"
}
Perhaps the following blog post gives you an idea how to do so. https://lazyadmin.nl/it/connect-to-google-api-with-powershell/
Upvotes: 29