【问题标题】:MongoDB ssl via C# driver: The remote certificate is invalid according to the validation procedureMongoDB ssl via C# driver:远程证书根据验证程序无效
【发布时间】:2016-01-11 16:15:46
【问题描述】:

我正在尝试使用从 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

证书文件是通过关注these instructions生成的。

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");           
    }

最后一行抛出异常:Unable to connect to server 127.0.0.1:27017: The remote certificate is invalid according to the validation procedure.

有谁知道如何让它工作?

【问题讨论】:

    标签: c# mongodb ssl


    【解决方案1】:

    检查 CRL 是否有效。

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

    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吗?
    【解决方案2】:

    Nambi's answer 帮助我发现了问题。自签名根证书不受信任。将 mongodb-cert.crt 添加到 Certificates (Local Computer) 管理单元下的 Trusted Root Certification Authorities 后,该问题就消失了。 p>

    【讨论】:

      猜你喜欢
      • 2022-07-06
      • 2016-01-07
      • 1970-01-01
      • 2011-03-28
      • 2016-11-28
      • 2021-09-16
      • 2013-08-08
      相关资源
      最近更新 更多