Skip to content

Instantly share code, notes, and snippets.

@Jaykul
Last active August 5, 2023 23:36
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Jaykul/74508c0c8425e6d5d300caa84c8f873f to your computer and use it in GitHub Desktop.
Save Jaykul/74508c0c8425e6d5d300caa84c8f873f to your computer and use it in GitHub Desktop.
ServerCertificateValidationCallback (or rather, collector) for .NET Core
[CmdletBinding()]
param(
[Parameter(Mandatory)]
[Uri]$url
)
Add-Type -TypeDefinition @'
using System;
using System.Net.Http;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
public static class CertHelper {
static X509Certificate2 LastCert;
#nullable enable
public static bool Validate(HttpRequestMessage requestMessage, X509Certificate2? certificate, X509Chain? chain, SslPolicyErrors sslErrors) {
if (certificate == null) {
return false;
}
LastCert = new X509Certificate2(certificate);
return true;
}
public static X509Certificate2 GetCertificate(Uri url) {
var handler = new HttpClientHandler();
handler.ServerCertificateCustomValidationCallback = Validate;
var client = new HttpClient(handler);
HttpResponseMessage response = client.GetAsync(url).Result;
response.EnsureSuccessStatusCode();
return LastCert;
}
}
'@
$certificate = [CertHelper]::GetCertificate($url)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment