Powershell Invoke-Restmethod Authorization Header

Powershell Invoke-Restmethod Authorization Header

While invoking an Invoke-RestMethod using Powershell like:

Invoke-RestMethod -Method Get -Uri "" -Headers $headers

and $headers being

$headers = @{
    Authorization="Secret $username $password"
    Content='application/json'
}

What is the format expected for the parameters $username and $password?

3 Answers

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.

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

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 "" -ContentType application/json -Body $body

The ContentType is set, because I expect JSON in response.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.