简体   繁体   中英

Can't establish SSL connection to MongoDB from NodeJS program

I am trying to connect a mongod instance from NodeJS program using Mongoose that configured with SSL connection but I'm getting the following error on the mongod console: "Error receiving request from client: SSLHandshakeFailed: The server is configured to only allow SSL connections."

The mongod instance is initiated as follow:

mongod --sslMode requireSSL --sslPEMKeyFile C:/Users/MyUsername/Path/mongodb.pem

I tried to use MongoClient instead of mongoose but nothing new happened. This is my piece of code:

if(envConfig.config.db.tls === true){
     let certFile = [fs.readFileSync("C:/PATH/TO/Key/mongoDB.pem")];
     mongoose.connect("mongodb://localhost:27017/DB_NAME?ssl=true",{
         server:{
             sslValidate: true,
             sslCA: certFile
         }
     });
 }else{
       mongoose.connect(`mongodb://${dbUrl}`,options);
 }

It is not something about the PEM file because when I start the mongod as I wrote and use SSL connection with MongoDB Compass using the same PEM file from the code - it works.

MongoDB version: 3.6.0

Mongoose version: 4.13.6

Happy if someone will guide me what am I doing wrong.

I think you should refer to the question Mongoose SSL, connection not accepted

You should specify {server: {ssl: true} parameter and I think your problem will be solved

If you initiate MongoDB daemon with private key and certificate

mongod --sslMode requireSSL --sslPEMKeyFile C:/Users/MyUsername/Path/mongodb.pem --sslCAFile C:/Users/MyUsername/Path/mongodb.crt

You can connect from Node JS like

if(envConfig.config.db.tls === true){
 let key = fs.readFileSync("C:/Users/MyUsername/Path/mongodb.pem");
 let crt = fs.readFileSync("C:/Users/MyUsername/Path/mongodb.crt");
 mongoose.connect("mongodb://localhost:27017/DB_NAME?ssl=true",{
     server:{
         "sslValidate" :true
         "sslKey": key,
         "sslCert": crt, // if you have one certificate you can use `sslCert` parameter
     }
 });
}else{
  mongoose.connect(`mongodb://${dbUrl}`,options);
}

More detail explanation of SSL connection via Node JS you can go here

Solved! Problem was using express-session middelware and trying to connect the DB with incorrect connection string, that what caused the problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM