Skip to content

Instantly share code, notes, and snippets.

@juicemia
Created December 9, 2022 18:38
Show Gist options
  • Save juicemia/93ca1cd343ccfbf65d914da7a21dfcfa to your computer and use it in GitHub Desktop.
Save juicemia/93ca1cd343ccfbf65d914da7a21dfcfa to your computer and use it in GitHub Desktop.
CA certificate verification
var caCert = X509Certificate2.CreateFromPem(options.CaCertificate!);
clientSettings.CreateHttpMessageHandler = () =>
{
var httpSettings = new SocketsHttpHandler()
{
// This is taken from the default implementation.
KeepAlivePingDelay = clientSettings.ConnectivitySettings.KeepAliveInterval,
KeepAlivePingTimeout = clientSettings.ConnectivitySettings.KeepAliveTimeout,
};
httpSettings.SslOptions.RemoteCertificateValidationCallback = (
sender,
certificate,
chain,
errors) =>
{
if (errors == SslPolicyErrors.None)
return true;
if (errors != SslPolicyErrors.RemoteCertificateChainErrors)
{
logger.LogInformation("got SSL policy errors {Errors}", errors);
return false;
}
if (certificate == null)
{
logger.LogInformation("unable to validate eventstore cert: missing certificate");
return false;
}
if (chain == null)
{
logger.LogInformation(
"unable to validate eventstore cert: missing chain");
return false;
}
chain!.ChainPolicy.CustomTrustStore.Clear();
chain.ChainPolicy.TrustMode = X509ChainTrustMode.CustomRootTrust;
chain.ChainPolicy.CustomTrustStore.Add(caCert);
var valid = chain.Build(new X509Certificate2(certificate!));
if (!valid)
{
logger.LogInformation("certificate failed validation");
}
return valid;
};
return httpSettings;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment