node.jsmongodb

MongoDB Authentication failed


I have a very simple node.js snippet:

const mongodb = require("mongodb");

process.env = Object.assign({
    DATABASE_HOST: "127.0.0.1",
    DATABASE_PORT: 27017,
    DATABASE_NAME: "cd0a3d59-c3cf-47a6-a6c3-fd134e7697c9",
    DATABASE_AUTH_USERNAME: "cd0a3d59-c3cf-47a6-a6c3-fd134e7697c9",
    DATABASE_AUTH_PASSWORD: "3732868e7dc810a06b2ddfb4257d43c57e0612b1c842a9e1a762c5a3b0628905"
}, process.env);

console.log("Init Database...");


mongodb.MongoClient.connect(`mongodb://${process.env.DATABASE_HOST}:${process.env.DATABASE_PORT}/${process.env.DATABASE_NAME}`, {
    auth: {
        username: process.env.DATABASE_AUTH_USERNAME,
        password: process.env.DATABASE_AUTH_PASSWORD
    },
    useUnifiedTopology: true,
    useNewUrlParser: true,
}, async (err, client) => {

    console.log(err || client)

});

I cant authenticate with the credentials.

Init Database...
MongoServerError: Authentication failed.
    at Connection.onMessage (/home/marc/projects/OpenHaus/backend/node_modules/mongodb/lib/cmap/connection.js:231:30)
    at MessageStream.<anonymous> (/home/marc/projects/OpenHaus/backend/node_modules/mongodb/lib/cmap/connection.js:61:60)
    at MessageStream.emit (node:events:518:28)
    at processIncomingData (/home/marc/projects/OpenHaus/backend/node_modules/mongodb/lib/cmap/message_stream.js:125:16)
    at MessageStream._write (/home/marc/projects/OpenHaus/backend/node_modules/mongodb/lib/cmap/message_stream.js:33:9)
    at writeOrBuffer (node:internal/streams/writable:564:12)
    at _write (node:internal/streams/writable:493:10)
    at Writable.write (node:internal/streams/writable:502:10)
    at Socket.ondata (node:internal/streams/readable:1007:22)
    at Socket.emit (node:events:518:28) {
  ok: 0,
  code: 18,
  codeName: 'AuthenticationFailed',
  connectionGeneration: 0,
  [Symbol(errorLabels)]: Set(2) { 'HandshakeError', 'ResetPool' }
}

mongosh -u cd0a3d59-c3cf-47a6-a6c3-fd134e7697c9 -p 3732868e7dc810a06b2ddfb4257d43c57e0612b1c842a9e1a762c5a3b0628905 works without any issues.

And when i login as "admin", i can see the user:

test> use admin
switched to db admin
admin> db.getUsers()
{
  users: [
    {
      _id: 'admin.cd0a3d59-c3cf-47a6-a6c3-fd134e7697c9',
      userId: UUID('8f617eac-07ea-4f66-af5f-ff8fbc3aa94e'),
      user: 'cd0a3d59-c3cf-47a6-a6c3-fd134e7697c9',
      db: 'admin',
      roles: [
        {
          role: 'readWrite',
          db: 'cd0a3d59-c3cf-47a6-a6c3-fd134e7697c9'
        }
      ],
      mechanisms: [ 'SCRAM-SHA-1', 'SCRAM-SHA-256' ]
    },
    {
      _id: 'admin.root',
      userId: UUID('20f259d2-9e6c-43d0-9360-ec2147595132'),
      user: 'root',
      db: 'admin',
      roles: [ { role: 'root', db: 'admin' } ],
      mechanisms: [ 'SCRAM-SHA-1', 'SCRAM-SHA-256' ]
    }
  ],
  ok: 1
}

Whats the problem with my node.js?


Solution

  • The problem has to do with the fact that you are supplying a database name in the connection string (/${process.env.DATABASE_NAME}) but the user that you are trying to authenticate with is stored in the admin database.

    Per the docs:

    Connection String Database Options

    You can specify a default database in the [/defaultauthdb] field of the connection string. The client uses the specified [/defaultauthdb] database as the default database. If unspecified by the connection string, the default database is the test database.

    You can specify the authentication database in your connection string using the authSource connection option. If specified, the client uses this database to verify your user identity and credentials. If authSource is unspecified, it defaults to the [/defaultauthdb] database. If both authSource and [/defaultauthdb] are unspecified, authSource defaults to the admin database.

    The following connection string sets the default database to myDefaultDB and the authentication database to admin:

    mongodb://myDatabaseUser:D1fficultP%40ssw0rd@mongodb0.example.com:27017/myDefaultDB?authSource=admin
    

    Appending ?authSource=admin to your connection string should resolve the problem.