【问题标题】:Mongoose not sending SSL cert to MongoDB serverMongoose 不向 MongoDB 服务器发送 SSL 证书
【发布时间】:2017-09-26 17:04:14
【问题描述】:

我在将某些自签名 SSL 证书与 Mongoose 一起使用时遇到问题。让我挂断电话的是,我可以使用普通的 Mongo Node 客户端很好地连接到数据库服务器,但是当我尝试使用与 Mongoose.createConnection 完全相同的配置进行连接时,我收到一条错误消息,内容为“[conn1 ] 当我检查 Mongod 日志时,没有对等方提供 SSL 证书。

这是我用来连接 MongoClient.connect 的代码(有效):

var MongoClient = require('mongodb').MongoClient
var fs = require('fs')  

// Read the certificates
const ca = [fs.readFileSync(process.env.caPath)];
const cert = fs.readFileSync(process.env.certPath);
let urlPath = ["mongodb://", username, ":", password, "@", dburl, ":", port, "/collection?&ssl=true"]
let url = urlPath.join('')

// Connect validating the returned certificates from the server
const options = {
  server: {
    ssl: true,
    sslValidate: true,
    sslCA: ca,
    sslCert: cert
  }
}

MongoClient.connect(url, options, function(err, db) {
  do stuff
})

这是使用 Mongoose.createConnection 的代码(不起作用):

const mongoose = require('mongoose');
const fs = require('fs')

let urlPath = ["mongodb://", username, ":", password "@", dburl, ":", port, "/collection?&ssl=true"]
let url = urlPath.join('')

var ca = [fs.readFileSync(process.env.caPath, 'utf8')];
var cert = fs.readFileSync(process.env.certPath, 'utf8');

const options = {
  server: {
    ssl: true,
    sslValidate: true,
    sslCA: ca,
    sslCert: cert
  }
}
const connection = mongoose.createConnection(url, options)

根据Mongoose docs,这看起来是正确的连接方式,更奇怪的是,将服务器选项传递给 Mongoose.connect 似乎也可以。

谢谢!

【问题讨论】:

    标签: node.js mongodb ssl mongoose self-signed


    【解决方案1】:

    您需要在mongoose.connect() 上设置一些额外的身份验证选项(authMechanismauthSource)来指定 SSL 证书。 见:https://docs.mongodb.com/manual/reference/connection-string/#authentication-options

    这些可以指定为 mongoose 的选项,如下所示: options.auth = { authMechanism: 'MONGODB-X509', authSource: '$external' }

    然后使用这些选项进行连接:

    this.mongoose.connect(uri, options, (err) => { ...

    【讨论】:

      【解决方案2】:

      我遇到了同样的问题,但我发现这是因为我在同一个 .pem 文件中拥有了 cat 的密钥和证书(正如 mongodb 文档中所建议的那样)。

      但它很容易修复,只需在 sslCert:sslKey: 下指定相同的文件,如下所示:

      const options = {
          server: {
              ssl: true,
              sslValidate: true,
              sslCA: ca,
              sslCert: cert,
              sslKey: cert
          }
      }
      

      就我而言,没有必要指定authMechanismauthSource

      【讨论】:

        猜你喜欢
        • 2011-09-22
        • 1970-01-01
        • 2012-07-03
        • 1970-01-01
        • 2018-04-27
        • 2014-04-10
        • 2013-10-25
        • 2012-11-14
        • 2015-06-24
        相关资源
        最近更新 更多