PowerShell Invoke-RestMethod失败

问题描述 投票:0回答:2

我是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

返回:

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

rest powershell
2个回答
0
投票

If ClientId or Client_Secret has special characters, UrlEncode before sending request

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

正如您在客户端密钥和客户端ID中强调的那样,在进行Invoke-RestMethod之前,您应该对它们进行编码


0
投票

试试这个:

[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作为默认值

© www.soinside.com 2019 - 2024. All rights reserved.