Created
March 12, 2024 16:08
-
-
Save jkdba/889e9c929b86c0338b4272b0e3d1527b to your computer and use it in GitHub Desktop.
PowerShell 7 HttpClientHandler with custom Certification Validation Logic
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
using namespace System; | |
using namespace System.Net; | |
using namespace System.Net.Http; | |
## handler to bypass invalid certificate | |
$handler = [HttpClientHandler]::new() | |
# $handler.AllowAutoRedirect = $false | |
$handler.ServerCertificateCustomValidationCallback = [HttpClientHandler]::DangerousAcceptAnyServerCertificateValidator ## System.Net.Http. | |
$location = [Uri]::New("https://some_invalid_cert_server") | |
$client = [HttpClient]::new($handler) | |
$request = [HttpRequestMessage]::new([HttpMethod]::Get, $location) | |
$response = $client.Send($request) | |
## custom validation callback | |
if(-not ([System.Management.Automation.PSTypeName]'CustomNet.CertValidation').Type) | |
{ | |
Add-Type @" | |
using System; | |
using System.IO; | |
using System.Net.Security; | |
using System.Net.Sockets; | |
using System.Security.Cryptography.X509Certificates; | |
namespace CustomNet | |
{ | |
public static class CertValidation | |
{ | |
public static bool ValidateServerCertificate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) | |
{ | |
// bypass all certificate errors | |
return true; | |
// or validate the certificate like | |
// return certificate.Subject == "CN=yourserver.yourdomain.com"; | |
// or | |
// return certificate.GetCertHashString() == "your_cert_hash"; | |
// or | |
// return certificate.Issuer == "your_issuer"; | |
// or | |
// return certificate.Verify() == true; | |
// or | |
// return sslPolicyErrors == SslPolicyErrors.None; | |
} | |
public static RemoteCertificateValidationCallback GetCallback() | |
{ | |
return new RemoteCertificateValidationCallback(ValidateServerCertificate); | |
} | |
} | |
} | |
"@ | |
} | |
$handler = [HttpClientHandler]::new() | |
$handler.ServerCertificateCustomValidationCallback = [CustomNet.CertValidation]::GetCallback() ## CustomNet. | |
$location = [Uri]::New("https://some_invalid_cert_server") | |
$client = [HttpClient]::new($handler) | |
$request = [HttpRequestMessage]::new([HttpMethod]::Get, $location) | |
$response = $client.Send($request) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment