20

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?

KyleMit
  • 30,350
  • 66
  • 462
  • 664

3 Answers3

23

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/

rufer7
  • 3,369
  • 3
  • 22
  • 28
8

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."

iamattiq1991
  • 746
  • 9
  • 11
1

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.

Alex_P
  • 2,580
  • 3
  • 22
  • 37