Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unexpected error occurred running a simple unauthorized Rest query

I have a rest endpoint that doesn't perform an authentication check. I can run a simple curl commmand from Linux:

curl -k https://application/api/about

This responds.

However if try the following on PowerShell it fails:

Invoke-RestMethod https://application/api/about

Then I get:

Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a send.
At line:1 char:1
+ Invoke-RestMethod $Application
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand

Could some one please tell me how I can get around this problem ?

EDIT:

Trying with Invoke-WebRequest:

Invoke-WebRequest -Uri "https://application/api/about"

Invoke-WebRequest : The underlying connection was closed: An unexpected error occurred on a send. At line:1 char:1 + Invoke-WebRequest -Uri "https://application/api/a ... + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand

like image 764
dross Avatar asked Jan 27 '17 15:01

dross


3 Answers

Using:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12

Taken from Powershell 3.0 Invoke-WebRequest HTTPS Fails on All Requests.

like image 191
dross Avatar answered Oct 22 '22 20:10

dross


in my case the TLS trick did not work, this seems to be a bug in powershell. you need to add the callback using .net code instead of a scriptblock.

#C# class to create callback
$code = @"
public class SSLHandler
{
    public static System.Net.Security.RemoteCertificateValidationCallback GetSSLHandler()
    {

        return new System.Net.Security.RemoteCertificateValidationCallback((sender, certificate, chain, policyErrors) => { return true; });
    }

}
"@

#compile the class
Add-Type -TypeDefinition $code

#disable checks using new class
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = [SSLHandler]::GetSSLHandler()
#do the request
try
{
    invoke-WebRequest -Uri myurl -UseBasicParsing
} catch {
    # do something
} finally {
   #enable checks again
   [System.Net.ServicePointManager]::ServerCertificateValidationCallback = $null
}
like image 27
Justin Avatar answered Oct 22 '22 20:10

Justin


[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls -bor [Net.SecurityProtocolType]::Tls11 -bor [Net.SecurityProtocolType]::Tls12

Works in Windows server 2016

Major Minor Build Revision


5 1 17763 1007

like image 2
Anand Joshi Avatar answered Oct 22 '22 21:10

Anand Joshi