MongoDB ssl通过C#驱动程序:根据验证过程,远程证书无效

本文关键字:程证书 无效 证书 过程 验证 通过 ssl 驱动程序 MongoDB | 更新日期: 2023-09-27 18:30:01

我正在尝试使用从C#客户端到MongoDB的X.509自签名证书来测试身份验证。我已经成功地在控制台窗口中使用ssl运行mongod,并使用mongo命令从另一个控制台窗口连接到它:

mongod --clusterAuthMode x509 --sslMode requireSSL --sslPEMKeyFile mongodb.pem --sslCAFile client.pem

mongo --ssl --sslCAFile mongodb.pem --sslPEMKeyFile client.pem

证书文件是按照这些说明生成的。

MongoDB驱动程序需要我生成的pfx文件:

openssl pkcs12 -export -in client.pem -inkey client-cert.key -out client.pfx

实际代码如下:

    private static void TryConnect()
    {
        var cert = new X509Certificate2(@"C:'Program Files'MongoDB'Server'3.2'bin'client.pfx", "test");
        var settings = new MongoClientSettings
        {
            Credentials = new[]
            {
                MongoCredential.CreateMongoX509Credential("subject= emailAddress=test@test.com,CN=127.0.0.1,OU=Test,O=Test,L=Cph,C=DK")
            },
            SslSettings = new SslSettings
            {
                ClientCertificates = new[] { cert },
            },
            UseSsl = true
        };
        settings.Server = new MongoServerAddress("127.0.0.1");            
        MongoClient client = new MongoClient(settings);
        var db = client.GetServer().GetDatabase("test");
        db.CreateCollection("test");           
    }

最后一行抛出异常:无法连接到服务器127.0.0.1:27017:根据验证过程,远程证书无效

有人知道怎么做吗?

MongoDB ssl通过C#驱动程序:根据验证过程,远程证书无效

检查CRL是否有效。

以下链接描述了在另一个场景(与mongodb无关)中导致此问题的HTTP URL中的错误配置

http://www.coretekservices.com/2014/jun/26/certificate-services-did-not-start-sub-ca

您可以通过验证证书和检查策略错误来获得更多信息(注意警告)

警告:请勿在生产中使用此产品!!!立即解决特定问题

 settings.SslSettings = new SslSettings
        {
            ClientCertificates = new[] { cert },
            ServerCertificateValidationCallback = delegate (object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
            {
                foreach (var item in chain.ChainElements)
                {
                    foreach (var elemStatus in item.ChainElementStatus)
                    {
                        Console.WriteLine( item.Certificate.Subject + "->" + elemStatus.StatusInformation);
                    }
                }
                return true; //NOT FOR PRODUCTION: this line will bypass certificate errors.
            }
       }

Nambi的回答帮助我确定了问题。自签名根证书不受信任。mongodb-cert.crt添加到证书(本地计算机)管理单元下的受信任的根证书颁发机构后,该问题消失了。