Last active
August 5, 2023 23:36
-
-
Save Jaykul/74508c0c8425e6d5d300caa84c8f873f to your computer and use it in GitHub Desktop.
ServerCertificateValidationCallback (or rather, collector) for .NET Core
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[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