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

Viewed 356

I am getting this issue while trying to get the project details from GCP using the following API using local ISE. I use the below code to get token and hit the GCP.

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}
$Uri = "https://IpAddress/api/token/gcp/" 
$jwtToken = Invoke-RestMethod -Uri $Uri -Method POST -ContentType "application/json" -Body {}
$token = $jwtToken.access_token   
$getUrl = "https://cloudresourcemanager.googleapis.com/v3/projects/XXXXXXXXX"
$headers = @{'Content-Type'='application/json';'Authorization'='Bearer $token'}
$getTags = Invoke-RestMethod -Uri $getUrl -Method Get -Headers $headers

First 4 lines of the script is used to get the token, which is used to get the project details. when I tried to get the token without this [System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true} got similar error.

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

To sort out this, I have added the below line of code to my script

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}

Is the above line disturbing the whole script? or is there anything that I am missing. Can any one help me to sort this error.

Thank you

1 Answers

[Update]

Your problem is with this line of code:

$Uri = "https://IpAddress/api/token/gcp/"

Only self-signed certificates have an IP address for the CN (common name). That is why the certificate validation is failing.

Change IpAddress to the domain name. If your service does not have a domain name that matches the SSL certificate, then you must disable certificate validation or write a custom validator that knows the hash value of your self-signed certificate.

[End Update]

By setting ServerCertificateValidationCallback to return true, you are preventing certificate validation (ignoring certificate errors).

Do not disable certificate validation.

You have an underlying problem, either with root certificates or the TLS protocol version.

Replace

[System.Net.ServicePointManager]::ServerCertificateValidationCallback = {$true}

With

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