PowerShell调用RestMethod失败
我是PowerShell的新手,正在尝试对需要OAuth2.0身份验证的应用程序使用REST方法 我以此为参考,写了以下内容:PowerShell调用RestMethod失败,rest,powershell,Rest,Powershell,我是PowerShell的新手,正在尝试对需要OAuth2.0身份验证的应用程序使用REST方法 我以此为参考,写了以下内容: $ClientID = 'david_web' $client_Secret = 'Secret_123' $Uri = "https://target_server/api/token" $Body = "grant_type=password=$ClientID&username=$client_Secret" $admAuth=Invoke-Rest
$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'
当我运行此命令时,我得到:
调用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\visualstudio 2015\Projects\PSDiscovery\REST\GetToken.ps1:34[错误]字符:12
[错误]+$admAuth=Invoke RestMethod-Method Post-Uri$Uri-Body$Body
[错误]+~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
[错误]+类别信息:无效操作:(System.Net.HttpWebRequest:Htt
[错误]pWebRequest)[调用RestMethod],WebException
[错误]+FullyQualifiedErrorId:WebCmdletWebResponseException,Microsoft.PowerShe
[错误]ll.Commands.InvokeRestMethodCommand如果ClientId或Client\u Secret具有特殊字符,请在发送请求之前进行URL编码
$clientedencoded=[System.Web.HttpUtility]::UrlEncode($ClientID)
$client\u secretncode=[System.Web.HttpUtility]::UrlEncode($client\u Secret)
由于客户机机密和客户机ID中有下划线,您可能应该对它们进行编码,然后再调用RestMethod
[Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::TLS12
您只需要在一个会话中使用这一行。它工作得很好
似乎没有办法将TLS1.2设为默认值,因为这篇文章将生成
grant\u type=password=$ClientID&username=$client\u Secret
以获得您想要的(grant\u type=password&username=david\u web&password=Secret\u 123
)你需要使用grant\u type=password&username=$ClientID&password=$client\u Secret'
OK-我也试过了-请参阅上面帖子中的编辑。