Search This Blog

27/03/2015

Invoke-RestMethod and self-signed certificates

As part of my study of Powershell I tried to connect to some REST API using an encrypted connection to a dev webserver. As it's a dev server the certificate is self signed so not "valid" for Powershell scripts

First problem

PS C:\Users\Frank> $headers = @{accept = "application/json"}
PS C:\Users\Frank> Invoke-RestMethod -Uri $uri/session -Method Post -Body $jsonCred -ContentType application/json -SessionVariable xsSession -Headers $headers

Invoke-RestMethod : The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.
At line:1 char:1
+ Invoke-RestMethod -Uri $uri/session -Method Post -Body $jsonCred -ContentType ap ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-RestMethod], WebException
    + FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeRestMethodCommand


Wrong solution found on Internet

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
This command will work only for the first call of invoke-restmethod or invoke-webmethod, any further call to Invoke-RestMethod will FAIL with this message
"Invoke-RestMethod : The underlying connection was closed: An unexpected error occurred on a send."


Good solution

I found the following piece of code to work perfectly. Copy paste it in your script or directly in the powershell windows shell.
Original solution post

# Only to ignore certificates errors
add-type @"
        using System.Net;
        using System.Security.Cryptography.X509Certificates;

            public class IDontCarePolicy : ICertificatePolicy {
            public IDontCarePolicy() {}
            public bool CheckValidationResult(
                ServicePoint sPoint, X509Certificate cert,
                WebRequest wRequest, int certProb) {
                return true;
            }
        }
"@
[System.Net.ServicePointManager]::CertificatePolicy = new-object IDontCarePolicy
# From now on the Invoke-restMethod and Invoke-webmethod calls will work with an invalid certificate

Ciao

No comments:

Post a Comment