我在我的 linux 机器上创建了自签名证书,其中我提供了与该 linux 的 IP 相同的证书 CN 我已经在 mongodb.conf 中添加了它们并重新启动了服务器 我可以通过命令连接
mongo --ssl --sslPEMKeyFile /etc/ssl/mongodbcerts/mongodb.pem --sslCAFile /etc/ssl/mongodbcerts/ca.pem
但是当我尝试从 nodeJS mongoose 连接时,我收到了类似的错误
MongooseServerSelectionError:主机名/IP 与证书的替代名称不匹配:IP:XXX.xx.x.xx 不在证书列表中:
我的nodejs连接mongodb的代码如下
const connectionOptions = { useCreateIndex: true,
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false ,
server:{
ssl: true,
sslValidate:true,
sslCA: require('fs').readFileSync("/etc/ssl/mongodbcerts/ca.pem"),
sslKey:require('fs').readFileSync("/etc/ssl/mongodbcerts/mongodb.key"),
sslCert:require('fs').readFileSync("/etc/ssl/mongodbcerts/mongodb.crt")
}
};
let mongo_url="mongodb://username:password@IPaddress/DB"
console.log(mongo_url)
mongoose.connect(mongo_url,connectionOptions).then(() => console.log( 'Database Connected' ))
.catch(err => console.log( err ));;
请告诉我错误
答案 0 :(得分:0)
我犯的错误是我创建了自签名证书,使用通用名称(CN)作为 IP 地址(XXX.xx.x.xx),但我们需要创建使用 CN 作为主机名的自签名证书。 要获取主机名,请打开 mongo shell 并执行以下命令:
>getHostName()
您将使用该 VM 的主机名并创建具有相同主机名的自签名证书,然后尝试与 mongoose nodejs 连接。它会起作用。 支持文档:https://mongoosejs.com/docs/tutorials/ssl.html
答案 1 :(得分:0)
我最近遇到了 this issue。从 MongoDB 4.2 开始,在进行 SAN 比较时,MongoDB 也支持 IP 地址的比较。您可以在 CN 字段中使用 IP 地址,但请确保您的 openssl 配置文件在 alt_names 部分包含您的服务器 IP 地址。
这是官方 MongoDB 文档中提供的示例 cnf 文件 -
# NOT FOR PRODUCTION USE. OpenSSL configuration file for testing.
[ req ]
default_bits = 4096
default_keyfile = myTestServerCertificateKey.pem ## The default private key file name.
default_md = sha256
distinguished_name = req_dn
req_extensions = v3_req
[ v3_req ]
subjectKeyIdentifier = hash
basicConstraints = CA:FALSE
keyUsage = critical, digitalSignature, keyEncipherment
nsComment = "OpenSSL Generated Certificate for TESTING only. NOT FOR PRODUCTION USE."
extendedKeyUsage = serverAuth, clientAuth
subjectAltName = @alt_names
[ alt_names ]
DNS.1 = ##TODO: Enter the DNS names if using hostname, otherwise remove this line
IP.1 = ##TODO: Enter the IP address if using IP address
[ req_dn ]
countryName = Country Name (2 letter code)
countryName_default = TestServerCertificateCountry
countryName_min = 2
countryName_max = 2
stateOrProvinceName = State or Province Name (full name)
stateOrProvinceName_default = TestServerCertificateState
stateOrProvinceName_max = 64
localityName = Locality Name (eg, city)
localityName_default = TestServerCertificateLocality
localityName_max = 64
organizationName = Organization Name (eg, company)
organizationName_default = TestServerCertificateOrg
organizationName_max = 64
organizationalUnitName = Organizational Unit Name (eg, section)
organizationalUnitName_default = TestServerCertificateOrgUnit
organizationalUnitName_max = 64
commonName = Common Name (eg, YOUR name)
commonName_max = 64