0
votes

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_Secr‌​et'    
$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

2
grant_type=password=$ClientID&username=$client_Secret will produce grant_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 use grant_type=password&username=$ClientID&password=$client_Secret' Daniel Morritt
OK - I have tried this as well - please see edit in post above.dross

2 Answers

0
votes

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)

As you have underscore in the client secret and Client ID, you should probably encode them, before doing Invoke-RestMethod

0
votes

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/