我尝试使用连接字符串连接到 MongoDB,但失败了。我确信我拥有的证书是正确的,因为我可以在 cmd 中使用此命令连接到数据库:
mongo --tls --tlsCAFile D:\DEV\ca-valid.pem --tlsCertificateKeyFile D:\DEV\mongo-valid.pem --host localhost --port 27017 --username admin --password test --authenticationDatabase admin
但是,当我尝试从 .net 连接时,出现此错误:
{"t":{"$date":"2024-05-23T15:12:11.684+01:00"},"s":"I", "c":"NETWORK", "id":22988, "ctx":"conn11603","msg":"Error receiving request from client. Ending connection from remote","attr":{"error":{"code":141,"codeName":"SSLHandshakeFailed","errmsg":"no SSL certificate provided by peer; connection rejected"},"remote":"127.0.0.1:52931","connectionId":11603}}
这是我正在使用的连接字符串:
mongodb://admin:test@localhost:27017/?tls=true&tlsCertificateKeyFile=D%3A%5CDEV%5Cmongo-valid.pem&tlsCAFile=D%3A%5CDEV%5Cca-valid.pem&authSource=admin
我应该提到,在启用 TLS 之前,我能够使用连接字符串连接到 mongo DB。
这是我的 mongod 配置文件:
port: 27017
bindIp: 127.0.0.1
tls:
mode: requireTLS
certificateKeyFile: D:\DEV\mongo-valid.pem
CAFile: D:\DEV\ca-valid.pem
更奇怪的是,如果我使用 MongoDB Compass,我可以通过如下所示的连接字符串连接到数据库:
mongodb://localhost:27017/?tls=true&tlsCertificateKeyFile=D%3A%5CDEV%5Cmongo-valid.pem&tlsCAFile=D%3A%5CDEV%5Cca-valid.pem
我接下来可以尝试什么有什么建议吗?
正如评论中提到的,.NET/C# 驱动程序不支持 PEM 文件的证书。另外,正如我的评论中提到的,使用客户端证书没有多大意义,除非您喜欢将其用于 x.509 客户端身份验证
您可以尝试将 CA
ca-valid.pem
导入到 Windows 证书存储中,请参阅将证书添加到客户端上的证书存储中。那么也许可以(我没有测试)简单地使用这个连接字符串进行连接
mongodb://localhost:27017/?tls=true
我假设驱动程序默认使用证书存储中的 CA。