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
grant_type=password=$ClientID&username=$client_Secret
will producegrant_type=password=david_web&username=Secret_123
, to get what you want (grant_type=password&username=david_web&password=Secret_123
) you'll need to usegrant_type=password&username=$ClientID&password=$client_Secret'
– Daniel Morritt