【发布时间】: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_Secret'
$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