I am pretty new to PowerShell and am trying to use REST methods for an application which require OAuth2.0 Authentication.
I have written the following using this https://msdn.microsoft.com/en-us/library/hh454950.aspx as a reference:
$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'
When I run this I get:
Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a send.
If I try the following from Linux:
curl -k -i -X POST -d 'grant_type=password&username=david_web&password=Secret_123' https://target_server/api/token
It works but I have to include the -k option. How do I do the same on PowerShell?
Edit:
Running just this:
$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
Returns:
[ERROR] Invokenvoke-RestMethod : The underlying connection was closed: An unexpected error [ERROR] occurred on a send. [ERROR] At C:\\data\\visual studio 2015\\Projects\\PSDiscovery\\REST\\GetToken.ps1:34 [ERROR] char:12 [ERROR] + $admAuth = Invoke-RestMethod -Method Post -Uri $Uri -Body $Body [ERROR] + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ [ERROR] + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:Htt [ERROR] pWebRequest) [Invoke-RestMethod], WebException [ERROR] + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShe [ERROR] ll.Commands.InvokeRestMethodCommand
$clientIDEncoded = [System.Web.HttpUtility]::UrlEncode($ClientID) $client_SecretEncoded = [System.Web.HttpUtility]::UrlEncode($client_Secret)
As you have underscore in the client secret and Client ID, you should probably encode them, before doing Invoke-RestMethod
Try this:
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::TLS12
You need this line only once in one session. It works well.
There seems no way to make TLS1.2 as default as per this post https://powershell.org/forums/topic/is-it-possible-to-enable-tls-1-2-as-default-in-powershell/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.