Using Invoke-RestMethod and ignoring self-signed or expired certs

by Mar 10, 2015

 

I have written a script where I am making adjustment to my InfoBlox system through the rest API and when I tried running the script from a non elevated  prompt, I got errors like these below:

 

The underlying connection was closed: Could not establish trust relationship for the SSL/TLS secure channel.

The underlying connection was closed: An unexpected error occurred on a send.

It turns out that it has a self-signed cert, that is not trusted by my computer.  

 

I added this function:

function Ignore-SelfSignedCerts {
    add-type -TypeDefinition  @"
        using System.Net;
        using System.Security.Cryptography.X509Certificates;
        public class TrustAllCertsPolicy : ICertificatePolicy {
            public bool CheckValidationResult(
                ServicePoint srvPoint, X509Certificate certificate,
                WebRequest request, int certificateProblem) {
                return true;
            }
        }
"@
    [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy
}#function
And then I called the function in my Begin block of my main function:
Ignore-SelfSignedCerts

 

This can also just be added with the code(either the script or function):

add-type -TypeDefinition  @"
        using System.Net;
        using System.Security.Cryptography.X509Certificates;
        public class TrustAllCertsPolicy : ICertificatePolicy {
            public bool CheckValidationResult(
                ServicePoint srvPoint, X509Certificate certificate,
                WebRequest request, int certificateProblem) {
                return true;
            }
        }
"@
    [System.Net.ServicePointManager]::CertificatePolicy = New-Object TrustAllCertsPolicy

 

Helpful info!