Mongoose connection authentication failed

Viewed 27820

With this help, I created a super user in the mongo shell: Create Superuser in mongo

user: "try1"
passw: "hello"

In mongo cmd, I have 3 databases: 'admin', 'myDatabase' and 'local'.

Now I try to use this authorized connection to the database called 'myDatabase'.

mongoose.connect('mongodb://try1:hello@localhost:27017/myDatabase');

But this is the error I get:

name: 'MongoError',
message: 'Authentication failed.',
ok: 0,
errmsg: 'Authentication failed.',
code: 18,
codeName: 'AuthenticationFailed' }
Mongoose disconnected
Mongoose disconnected through ${msg}

11 Answers

Further to @kartGIS, I've added one more option to make the connection code perfect as possible.

mongoose.connect("mongodb://localhost:27017/databaseName", {
    "auth": { "authSource": "admin" },
    "user": "username",
    "pass": "password",
    "useMongoClient": true
});

This is the correct answer now. others are not completely correct.

await mongoose.connect("mongodb://localhost:27017/db", {
poolSize: 10,
authSource: "admin",
user: "admin",
pass: "password",
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false, });

Working fine for me on Mongodb 4.2 and Mongoose 5.7.13

Node.js

const Connect = async () => {

    let url = "mongodb://localhost:27017/test_db";

    try {

        let client = await Mongoose.connect( url, {
            poolSize: 10,
            authSource: "admin",
            user: "root",
            pass: "root123", 
            useCreateIndex: true,
            useNewUrlParser: true,
            useUnifiedTopology: true
        } );

        log( "Database is connected!" );
    } catch ( error ) {
        log( error.stack );
        process.exit( 1 );
    }

}
Connect();

/etc/mongod.conf

systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

storage:
  dbPath: /var/lib/mongo
  journal:
    enabled: true

processManagement:
  fork: true  # fork and run in background
  pidFilePath: /var/run/mongodb/mongod.pid  # location of pidfile
  timeZoneInfo: /usr/share/zoneinfo

net:
  port: 27017
  bindIp: 0.0.0.0 

setParameter:
   enableLocalhostAuthBypass: false

security:
  authorization: enabled

Database User

use admin;
db.createUser(
  {
    user: "root",
    pwd: "root123",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
  }
)

show users;
{
   _id": "admin.root",
   "userId": UUID( "5db3aafd-b1fd-4bea-925e-8a4bfb709f22" ),
   "user": "root",
   "db": "admin",
   "roles": [ {
        "role": "userAdminAnyDatabase",
        "db": "admin"
      },
      {
        "role": "readWriteAnyDatabase",
        "db": "admin"
      }
   ],
   "mechanisms": [
       "SCRAM-SHA-1",
       "SCRAM-SHA-256"
   ]
}

Sintaxis:

mongoose.connect('mongodb://username:password@host:port/database?authSource=admin'); 

Example:
mongoose.connect('mongodb://myUser:myPassword@localhost:27017/myDataBase?authSource=admin');

I have the same problem, and it solved by removing the 'authSource' param

/* Not working */
mongoose.connect("mongodb://localhost:27017/test", {
    "auth": { "authSource": "admin" },
    "user": "admin",
    "pass": "admin123",
    "useMongoClient": true
});

/* Working */
mongoose.connect("mongodb://localhost:27017/test", {
    "user": "admin",
    "pass": "admin123",
    "useMongoClient": true
});

Tested on Mongoose-v5.0.0.

I got MongoParseError: credentials must be an object with 'username' and 'password' properties when used above answers.
Add username password to auth object solved the issue

  try {
    await connect("mongodb://localhost:27017/dbname", {
      auth: { username: "root", password: "example" },
      authSource: "admin",
    });
    console.log("Connected to mongo db");
  } catch (error) {
    console.error("Error connecting to mongodb", error);
  }

mongodb version 5.0.2
mongoose 6.0.4

I had the same problem. I am using an older MongoDB instance. I simply added authSource=admin to the connection string and it solved the problem.

Respectively, if your authSource is the database ('myDB' in the example) itself and you are trying to use the ConnectionOption dbName, you have to match authSource.

await mongoose.connect('mongodb://localhost:27017,' {
  dbName: 'myDB',
  user: 'myUser',
  pass: 'asldjaskdj'
);

Will fail with error:

{
    "msg": "Authentication failed",
    "attr": {
        "mechanism": "SCRAM-SHA-1",
        "principalName": "myUser",
        "authenticationDatabase": "admin",
        "client": "...",
        "result": "UserNotFound: Could not find user \"myUser\" for db \"admin\""
    }
}

Adding authSource: 'myDB' to the connect options will work. Example:

await mongoose.connect('mongodb://localhost:27017,' {
  dbName: 'myDB',
  authSource: 'myDB',
  user: 'myUser',
  pass: 'asldjaskdj'
);

I also faced the same issue but resolved it with this mongoose.connect(mongodb://${dbUser}:${dbPwd}@${dbHost}:${dbPort}/userInfo?authSource=admin). Assuming you have the authentication setup in mongodb.

NOTE This answer is not answering original question but trying to help people in similar situation using NestJS

NestJS

@Module({
  imports: [
    MongooseModule.forRoot(
      'mongodb://mongo:27017/test',
      {
        auth: {
          username: 'root',
          password: 'test',
        },
        authSource: 'admin',
      },
    ),
  ],
})
export class AppModule {}
Related