Powershell Invoke-RestMethod 授权标头

Red*_*jun 6 invoke powershell-4.0

在调用Invoke-RestMethod使用 Powershell 时,例如:

Invoke-RestMethod -Method Get -Uri "https://google.com/api/GetData" -Headers $headers
Run Code Online (Sandbox Code Playgroud)

并且$headers存在

$headers = @{
    Authorization="Secret $username $password"
    Content='application/json'
}
Run Code Online (Sandbox Code Playgroud)

参数$username和 的预期格式是什么$password

ruf*_*er7 25

据我所知,您必须在请求标头中发送 OAuth2 令牌。

$headers = @{
    Authorization="Bearer $token"
}
Run Code Online (Sandbox Code Playgroud)

也许下面的博客文章可以让您了解如何做到这一点。 https://lazyadmin.nl/it/connect-to-google-api-with-powershell/


iam*_*991 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
Run Code Online (Sandbox Code Playgroud)

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