【问题标题】:PowerShell Invoke-RestMethod FailsPowerShell 调用-RestMethod 失败
【发布时间】:2017-01-27 11:46:38
【问题描述】:

我是 PowerShell 的新手,我正在尝试将 REST 方法用于需要 OAuth2.0 身份验证的应用程序。

我使用https://msdn.microsoft.com/en-us/library/hh454950.aspx 作为参考编写了以下内容:

$ClientID = 'david_web'
$client_Secret = 'Secret_123'

$Uri = "https://target_server/api/token"

$Body = "grant_type=password=$ClientID&username=$client_Secret"

$admAuth=Invoke-RestMethod -Uri $Uri -Body $Body -Method Post

$HeaderValue = "Bearer " + $admauth

$uri = "https://target_server/api/v1.0/discovery";

$result = Invoke-RestMethod -Uri $uri -Headers @{Authorization = $HeaderValue} 

$result.string.'#text'

当我运行它时,我得到:

Invoke-RestMethod:底层连接已关闭:意外错误 发送时发生。

如果我从 Linux 尝试以下操作:

curl -k -i -X POST -d 'grant_type=password&username=david_web&password=Secret_123' https://target_server/api/token

它可以工作,但我必须包含 -k 选项。我如何在 PowerShell 上做同样的事情?

编辑:

只运行这个:

$ClientID = 'david_web'
$client_Secret = 'Secret_123'
$Uri = "https://target_server/api/token"
$Body = 'grant_type=password&username=$ClientID&password=$client_Secr‌​et'    
$admAuth = Invoke-RestMethod -Method Post -Uri $Uri -Body $Body

返回:

[ERROR] Invokenvoke-RestMethod : 底层连接已关闭:意外错误 [错误] 在发送时发生。 [错误] 在 C:\data\visual studio 2015\Projects\PSDiscovery\REST\GetToken.ps1:34 [错误] char:12 [错误] + $admAuth = Invoke-RestMethod -Method Post -Uri $Uri -Body $Body [错误] + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ ~~~~~~ [错误] + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:Htt [错误] pWebRequest) [Invoke-RestMethod], WebException [错误] + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShe [错误] ll.Commands.InvokeRestMethodCommand

【问题讨论】:

  • grant_type=password=$ClientID&username=$client_Secret 将产生grant_type=password=david_web&username=Secret_123,要得到你想要的(grant_type=password&username=david_web&password=Secret_123)你需要使用grant_type=password&username=$ClientID&password=$client_Secret'
  • 好的 - 我也试过了 - 请参阅上面帖子中的编辑。

标签: rest powershell


【解决方案1】:

如果ClientId或Client_Secret有特殊字符,发送请求前进行UrlEncode

$clientIDEncoded = [System.Web.HttpUtility]::UrlEncode($ClientID) $client_SecretEncoded = [System.Web.HttpUtility]::UrlEncode($client_Secret)

由于您在客户端密码和客户端 ID 中有下划线,您可能应该在执行 Invoke-RestMethod 之前对它们进行编码

【讨论】:

    【解决方案2】:

    试试这个:

    [Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::TLS12

    您在一个会话中只需要此行一次。效果很好。

    根据这篇文章https://powershell.org/forums/topic/is-it-possible-to-enable-tls-1-2-as-default-in-powershell/,似乎没有办法将 TLS1.2 设为默认值

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-29
      • 2015-02-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多