简体   繁体   中英

How would I connect to Mongodb using SSL certificate with mongoose@6.0.5 and Nodejs?

MongoDB shell version is v5.0.2

Before updating Mongoose everything was working fine but now it is showing me error in mongoose latest version. Thus I have to update MongoDB and node also. I have successfully setup SSL certificate and configure the mongod.conf file also. so I am able to access mongo shell through SSL certificates but my goal is connect through nodejs using mongoose.

I have no idea what I am missing from this code, it's giving me an error.

This is my code:

       var fs = require('fs')
       var mongoose = require('mongoose')
       var user_name = encodeURIComponent
        ('emailAddress=user@myemail.com,CN=127.0.0.1,OU=UNIT,O=DEMO,L=city,ST=test,C=AU')

       var ca = fs.readFileSync('/home/khurshid/Desktop/sslVal/my.crt');
       var clientcert = fs.readFileSync('/home/khurshid/Desktop/sslVal/user.crt');
       var clientkey = fs.readFileSync('/home/khurshid/Desktop/sslVal/user.key');
        
       mongoose.connect(`mongodb://${user_name}@127.0.0.1:27017/admin?authMechanism=MONGODB-X509 
       &authSource=$external&ssl=true&sslValidate=false`,
         {
            useNewUrlParser: true, 
            sslCA: ca, 
            sslCert: clientcert, 
            sslKey: clientkey
        }).catch((err) => {console.log(err)});
        
        console.log("connected to the database");
        mongoose.Promise = global.Promise;
        const customerSchema= new mongoose.Schema({ name: String,address: String,email:String,});

        const Customer= mongoose.model('Customer',customerSchema);

        async function createNewCustomer() {const customer= new Customer({name: 'new 
        customer',address: 'new address',email: 'customer1@new.com',});
        const result = await customer.save();
        console.log(result);
        }
        createNewCustomer();

Output

khurshid@khurshid:~/Desktop/sslVal$ node authsslcert509.js
connected to the database
Error: ENAMETOOLONG: name too long, open '-----BEGIN CERTIFICATE-----
44+WwbWbz87W0rUMubc/aIEF4Xr+wSFk4irqg43TFuBMjF42pqxbCybVx0OzIsdn
UcXOKmrMWJTK/8n92IqOnv+NanKXiJeXIK9EXK+eDjjMWoee/r+JZHeHwdVj3ISD
ozMpH+TSzrf4r8Ml3Tt2kHNe8ysB488EK0gu5+erZAguCk6G4n6XqW4HV/4hgQPo
VVe8IgFT8DBkqbCLMel/GRFB+zM1+VnevOLZxP7bLgAPyTtP6EjlMtHJGtwv9t7o
6QIDAQABo1MwUTAdBgNVHQ4EFgQU4shxBIIT4dKxwHo/UiMPh3XRFiMwHwYDVR0j
BBgwFoAU4shxBIIT4dKxwHo/UiMPh3XRFiMwDwYDVR0TAQH/BAUwAwEB/zANBgkq
hkiG9w0BAQsFAAOCAQEAvcRemDlzp77mKD6vZKXb7Hi9XSLg+GJ4DmyB9Ty4F+Lf
j/EO+HiSHbCuP6uBr/yF9ZcEi53b4pkwDgU1Q5sWdn8mp/Dl0bY3izAS8X6iMyVu
KDhwXqrTggzQZ+mqwolkD9qgsldheVgCN9tZm5KIAreFAl0NeOoW+jJrjdVFsZCh
jKkaTRySEkZ7w8Nu2I/0+NJMEZuN60gS9m+ZNk57WbCAR7jFJg69BvlZ/AkDHU3H
zmK9gB4nfivluVbuO0b03un5DvIROSvpscOIFQmZ8csmpmIzw883BQsm6jvgDy0b
siljnzkIUpEIqo9Mc9pULeTLEqME4WaCr7ODSIXGAQ==
-----END CERTIFICATE-----
'
    at Object.openSync (fs.js:498:3)
    at Object.readFileSync (fs.js:394:35)
    at transform (/home/khurshid/Desktop/sslVal/node_modules/mongodb/lib/connection_string.js:806:23)
    at setOption (/home/khurshid/Desktop/sslVal/node_modules/mongodb/lib/connection_string.js:394:36)
    at Object.parseOptions (/home/khurshid/Desktop/sslVal/node_modules/mongodb/lib/connection_string.js:287:9)
    at new MongoClient (/home/khurshid/Desktop/sslVal/node_modules/mongodb/lib/mongo_client.js:62:46)
    at /home/khurshid/Desktop/sslVal/node_modules/mongoose/lib/connection.js:781:16
    at new Promise (<anonymous>)
    at NativeConnection.Connection.openUri (/home/khurshid/Desktop/sslVal/node_modules/mongoose/lib/connection.js:778:19)
    at /home/khurshid/Desktop/sslVal/node_modules/mongoose/lib/index.js:330:10 {
  errno: -36,
  syscall: 'open',
  code: 'ENAMETOOLONG',
  path: '-----BEGIN CERTIFICATE-----\n' +
    '44+WwbWbz87W0rUMubc/aIEF4Xr+wSFk4irqg43TFuBMjF42pqxbCybVx0OzIsdn\n' +
    'UcXOKmrMWJTK/8n92IqOnv+NanKXiJeXIK9EXK+eDjjMWoee/r+JZHeHwdVj3ISD\n' +
    'ozMpH+TSzrf4r8Ml3Tt2kHNe8ysB488EK0gu5+erZAguCk6G4n6XqW4HV/4hgQPo\n' +
    'VVe8IgFT8DBkqbCLMel/GRFB+zM1+VnevOLZxP7bLgAPyTtP6EjlMtHJGtwv9t7o\n' +
    '6QIDAQABo1MwUTAdBgNVHQ4EFgQU4shxBIIT4dKxwHo/UiMPh3XRFiMwHwYDVR0j\n' +
    'BBgwFoAU4shxBIIT4dKxwHo/UiMPh3XRFiMwDwYDVR0TAQH/BAUwAwEB/zANBgkq\n' +
    'hkiG9w0BAQsFAAOCAQEAvcRemDlzp77mKD6vZKXb7Hi9XSLg+GJ4DmyB9Ty4F+Lf\n' +
    'j/EO+HiSHbCuP6uBr/yF9ZcEi53b4pkwDgU1Q5sWdn8mp/Dl0bY3izAS8X6iMyVu\n' +
    'KDhwXqrTggzQZ+mqwolkD9qgsldheVgCN9tZm5KIAreFAl0NeOoW+jJrjdVFsZCh\n' +
    'jKkaTRySEkZ7w8Nu2I/0+NJMEZuN60gS9m+ZNk57WbCAR7jFJg69BvlZ/AkDHU3H\n' +
    'zmK9gB4nfivluVbuO0b03un5DvIROSvpscOIFQmZ8csmpmIzw883BQsm6jvgDy0b\n' +
    'siljnzkIUpEIqo9Mc9pULeTLEqME4WaCr7ODSIXGAQ==\n' +
    '-----END CERTIFICATE-----\n'
}
(node:6585) UnhandledPromiseRejectionWarning: MongooseError: Operation `customers.insertOne()` buffering timed out after 10000ms
    at Timeout.<anonymous> (/home/khurshid/Desktop/sslVal/node_modules/mongoose/lib/drivers/node-mongodb-native/collection.js:149:23)
    at listOnTimeout (internal/timers.js:557:17)
    at processTimers (internal/timers.js:500:7)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:6585) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 2)
(node:6585) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
khurshid@khurshid:~/Desktop/sslVal$ 

Despite what the documentation says, the following worked for me with Mongoose 6.0.7.

    await mongoose.connect(process.env.DATABASE_URL, {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        ssl: true,
        sslValidate: true,
        sslCA: '/credentials/cabundle.crt',
        sslKey: '/credentials/client/service_bundled.pem',
        sslCert: '/credentials/client/service_bundled.pem'
    });

Instead of providing the file content, it is now only the path of the files needed.

SSL certificate will not go in place of username. Try the following ways to connect using ssl:

await mongoose.connect('mongodb://localhost:27017/test', {
  ssl: true,
  sslValidate: true,
  // For example, see https://medium.com/@rajanmaharjan/secure-your-mongodb-connections-ssl-tls-92e2addb3c89
  // for where the `rootCA.pem` file comes from
  sslCA: require('fs').readFileSync(`${__dirname}/rootCA.pem`)
});

Also remember

The SSL certificate's common name must line up with the host name in your connection string. If the SSL certificate is for hostname2.mydomain.com, your connection string must connect to hostname2.mydomain.com, not any other hostname or IP address that may be equivalent to hostname2.mydomain.com. For replica sets, this also means that the SSL certificate's common name must line up with the machine's hostname

Source: Documentation

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