0

I am trying to access Foreman API in Powershell version 5.1 using Invoke-RestMethod

I get following error:

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

I tried following command before the this command but it didn't work.

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

I tried with Tls, Tls11 also but it didn't work.

MohammadAmin Mohammadi
  • 1,183
  • 3
  • 14
  • 23
KP Singh
  • 1
  • 1
  • 3

1 Answers1

1

Are you connecting to an untrusted SSL certificate by any chance? You probably need to ignore trust errors as well as set the correct TLS version to use.

Add-Type @"
    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
Josh Wright
  • 422
  • 3
  • 12
  • I tried this but it didn't work. I am getting a different error: The underlying connection was closed: An unexpected error occurred on a send. – KP Singh Jul 16 '20 at 14:23
  • Any chance that you are trying to connect via a Proxy Server? If so, try running this as soon as you open a new PowerShell session, then try the Invoke. [Access web using Powershell and Proxy](https://stackoverflow.com/questions/14263359/access-web-using-powershell-and-proxy) – Josh Wright Jul 16 '20 at 14:37
  • The same code is working with Powershell Core 6 with -SkipCertificateCheck parameter. – KP Singh Jul 16 '20 at 15:21