How to connect to a server via TLS using MongoDB.Driver with a certificate file?

1.5k Views Asked by At

According to the MongoDB documentation it is supposed to be possible to connect via TLS where you specify the pem certificate by the tlsCAFile parameter.

However I have not been able to use the client in such a manner that it is successful.

[Installing the certificate to the local store is NOT an option]

All the client provides as an error is a generic A timeout occured after 30000ms... + The remote certificate is invalid according to the validation procedure regardless of what I've done. I have verified the server is accessible by MongoDB administrative tools by providing the cert explicitly to them.

2

There are 2 best solutions below

0
On BEST ANSWER

Eventually stumbled upon a solution to this:

var clientSettings = MongoClientSettings.FromUrl(new MongoUrl(mongoUrl));

clientSettings.UseTls = true;
clientSettings.SslSettings = new SslSettings
{
    EnabledSslProtocols = SslProtocols.Tls11,
    ServerCertificateValidationCallback = (sender, certificate, chain, errors) =>
        certificate.Subject.Contains("O=myOU,")
};

This is a looser validation but good enough for my needs. You could go with no-validation with => true or for full validation you could load the certificate into memory and verify the thumbprints match along with expiration dates being valid.

0
On

I've had the same problem while connecting to AWS-DocumentDB (that's compatible with MongoDB) and after struggling a few hours, Chris's answer worked perfectly.

I've just made a minor change just to verify if the certificate issuer is Amazon.

clientSettings.SslSettings = new SslSettings
{
    EnabledSslProtocols = SslProtocols.Tls11,
    ServerCertificateValidationCallback = (sender, certificate, chain, errors) =>
        certificate.Issuer.Contains("CN=Amazon")
};