Powershell Invoke-RestMethod授权标头

时间:2019-01-15 00:48:33

标签: invoke powershell-v4.0

使用Powershell调用Invoke-RestMethod时:

Invoke-RestMethod -Method Get -Uri "https://google.com/api/GetData" -Headers $headers

$headers

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

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

3 个答案:

答案 0 :(得分:0)

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

$headers = @{
    Authorization="Bearer $token"
}

也许以下博客文章为您提供了一个实现方法的想法。 https://lazyadmin.nl/it/connect-to-google-api-with-powershell/

答案 1 :(得分:0)

Rufer7 提供的解决方案是正确的。我只想添加一件事,您也可以在Invoke-WebRequest方法中传递content参数,以使标题像这样更简单,并以Json格式获取输出。因此,我的精炼脚本将如下所示。

Powershell脚本:

[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

仅当您看到此错误时,第一行才是可选的,否则您可以忽略此错误。

“ Invoke-WebRequest:请求已中止:无法创建SSL / TLS安全通道。”

答案 2 :(得分:0)

在我的场景中,我在REST API调用的主体中使用了usernamepassword。 我的身体是:

$body = [PSCustomObject] @{
  username=$Credential.UserName; 
  password=$Credential.GetNetworkCredential().Password;
} | ConvertTo-Json

在函数中,我使用PSCredential类:

[System.Management.Automation.PSCredential]
[System.Management.Automation.Credential()]
$Credential = [System.Management.Automation.PSCredential]::Empty,

最终,我这样称呼它:

Invoke-RestMethod -Method Get -Uri "https://google.com/api/GetData" -ContentType application/json -Body $body

已设置ContentType,因为我希望以JSON作为响应。