I've recently switched from using the PowerShell ISE to using Visual Studio Code
When I run my PowerShell scripts from within VSC on my office PC (Win 10 64Bit), none of the REST connections that use Invoke-RestMethod over HTTPS will authenticate against servers that use an unsigned SSL cert. When run from within VSC on my home PC (also Win 10 64bit), all works OK.
I have a function in the PowerShell that uses System.Net.Security to deal with unsigned SSL certs, which works perfectly when I run the code as native PowerShell or from the ISE
Here is how I compensate for Invoke-RestMethod connecting via SSL sessions with self-signed certs:
if (-not("dummy" -as [type])) {
add-type -TypeDefinition @"
using System;
using System.Net;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
public static class Dummy {
public static bool ReturnTrue(object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors sslPolicyErrors) {
return true;
}
public static RemoteCertificateValidationCallback GetDelegate() {
return new RemoteCertificateValidationCallback(Dummy.ReturnTrue);
}
}
"@
}
[System.Net.ServicePointManager]::ServerCertificateValidationCallback = [dummy]::GetDelegate()
[System.Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
I also encode the username + password into a Base64 encoded hash that is the header for the Invoke-RestMethod call:
$pair = "${username}:${password}"
$bytes = [System.Text.Encoding]::ASCII.GetBytes($pair)
$base64 = [System.Convert]::ToBase64String($bytes)
$basicAuthValue = "Basic $base64"
$headers = @{ Authorization = $basicAuthValue }
So the complete call sequence is:
Invoke-RestMethod -Uri "https://theserver.com/rest/api/whatever" -Method Get -Headers $headers
The server hosting the REST API, Confluence using Apache Tomcat, accepts the authentication when the PowerShell is run from within the ISE or executed directly, but throws back a response that the connection isn't authenticated if I try to run it from within VSC, but only on the PC at the office, not at home. I'm suspecting a security certificate issue or a policy interaction.
it doesn't work from VSC
? Any errors? – Robert Dyjas