Created
December 9, 2022 18:38
-
-
Save juicemia/93ca1cd343ccfbf65d914da7a21dfcfa to your computer and use it in GitHub Desktop.
CA certificate verification
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
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