Mongoose connection authentication failed
Asked Answered
A

15

27

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}

Annapolis answered 8/8, 2017 at 19:13 Comment(1)
So many answers - and most of them are just the same. Most of them are correct but none of them gives any explanation. See #63755242 to get some background information and explanation why it works or not work.Cerf
A
3

THIS ANSWER FOR MONGOOSE 6.7.0! USED IN NUXT 3

.env PART

MONGO_URI = "mongodb://localhost:27017/MyBeautifulDB"
MONGO_USERNAME = "mongoadmin"
MONGO_PASSWORD = "mystrongpassword"

DB CONNECTION PART

import mongoose from 'mongoose';

export default async (_nitroApp) => {
const config = useRuntimeConfig();

mongoose.connect(config.MONGO_URI, {
        maxPoolSize: 10,
        authSource: "admin",
        user: config.MONGO_USERNAME,
        pass: config.MONGO_PASSWORD
    })
    .then(() => console.log('Connected to DB'))
    .catch((e) => console.log(e));
}

nuxt.config.ts - Register your db connection file to configuration.

export default defineNuxtConfig({
    runtimeConfig: {
        MONGO_URI: process.env.MONGO_URI,
    },

    nitro: {
        plugins: ['@/server/db/index.ts']
    }
})
Alkanet answered 27/10, 2022 at 17:6 Comment(0)
F
49

I had the same problem many hours ago, and after all I solve it. My code is:

mongoose.createConnection(
  "mongodb://localhost:27017/dbName",
  {
    "auth": {
      "authSource": "admin"
    },
    "user": "admin",
    "pass": "password"
  }
);
Fourdimensional answered 8/8, 2017 at 22:28 Comment(4)
Why is mongoose documentation so difficult!? I had tried many variations of these but just did not try this one. Finally you saved my day. Thanks @FourdimensionalExcitant
what mongoose version are you using?Yoheaveho
thank you for that nice tip! @Yoheaveho I"m using "mongoose": "^5.9.24" on node: 14.6.0Dowson
For me at least, mongoose version 6.2.4, I would believe all versions >= 6 require the "authSource" without the "auth" parameter. so the "authSource" should be in the main JSON object.Mozarab
P
25

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 
});
Penneypenni answered 29/11, 2021 at 7:59 Comment(4)
authSource admin did the trick, this is my short version await mongoose.connect("mongodb://root:example@localhost:27017/example-db?authSource=admin"); ThxLaaspere
What happens if you move the user and pass to options, but authsource=admin is in the connection string, and if authSource admin is in options? I am facing the same issue. @asim-imamForespent
@Omkar, the first case you mentioned didn't work for me. I did that last year maybe I've also tried the second case you said. In my case, I was having trouble connecting admin to the database inside my ubuntu server.Penneypenni
What issue you're facing?Penneypenni
S
21

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
});
Skyjack answered 13/10, 2017 at 11:53 Comment(2)
can you explain what is this option "auth": { "authSource": "admin" },?Monosepalous
"auth": { "authSource": "admin" } means set authenticationDatabase to admin.Altruism
L
16

Syntax:

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

Example:

await mongoose.connect('mongodb://myUser:myPassword@localhost:27017/myDataBase?authSource=admin');
Longawa answered 7/10, 2021 at 19:40 Comment(1)
This worked. I simply added ?authSource=admin and it worked.Locular
C
11

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"
   ]
}
Cordiacordial answered 5/12, 2019 at 19:35 Comment(1)
For me, just add user, pass and authSource: "admin" and works like a charm. Thanks a lot.Virtually
T
6

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.

Thun answered 18/1, 2018 at 17:9 Comment(0)
A
3

THIS ANSWER FOR MONGOOSE 6.7.0! USED IN NUXT 3

.env PART

MONGO_URI = "mongodb://localhost:27017/MyBeautifulDB"
MONGO_USERNAME = "mongoadmin"
MONGO_PASSWORD = "mystrongpassword"

DB CONNECTION PART

import mongoose from 'mongoose';

export default async (_nitroApp) => {
const config = useRuntimeConfig();

mongoose.connect(config.MONGO_URI, {
        maxPoolSize: 10,
        authSource: "admin",
        user: config.MONGO_USERNAME,
        pass: config.MONGO_PASSWORD
    })
    .then(() => console.log('Connected to DB'))
    .catch((e) => console.log(e));
}

nuxt.config.ts - Register your db connection file to configuration.

export default defineNuxtConfig({
    runtimeConfig: {
        MONGO_URI: process.env.MONGO_URI,
    },

    nitro: {
        plugins: ['@/server/db/index.ts']
    }
})
Alkanet answered 27/10, 2022 at 17:6 Comment(0)
T
2

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

Thyroiditis answered 1/9, 2021 at 23:32 Comment(0)
S
2

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'
);
Solar answered 7/12, 2021 at 18:8 Comment(0)
T
1

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.

Truffle answered 15/8, 2021 at 19:5 Comment(0)
M
1

According to the latest documentation, it should be like this:

mongoose.connect("mongodb://localhost:27017/databaseName", {
    "user": "username",
    "pass": "password",
    "authSource": "databaseName" // users are scoped to DBs
});

Tested on mongoose6.x.x

Molini answered 29/12, 2022 at 20:57 Comment(0)
R
1

works for me. i use local database, and mongoose ver 6.9.1

.env file:

DB_HOST=127.0.0.1:27017
DB_NAME=blabla
DB_USER=blablabla
DB_PWD=blablablabla

js file:

const DB = `mongodb://${process.env.DB_HOST}/${process.env.DB_NAME}`;

mongoose
  .connect(DB, {
    authSource: 'admin',
    user: process.env.DB_USER,
    pass: process.env.DB_PWD,
  })
  .then(() => {
    console.log('Connected to database.');
  })
  .catch((err) => {
    console.log(err.message);
  });
Resistant answered 14/2, 2023 at 9:10 Comment(0)
T
0

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 {}
Tailband answered 1/4, 2022 at 11:15 Comment(0)
E
0

It helped me to write everything I needed in the options:

await mongoose.connect("mongodb://localhost:27017", {
            user: "root",
            pass: "secret",
            dbName: "motos",
   });
Extortioner answered 20/4 at 15:31 Comment(1)
How does this add more value on top of all the highly upvoted answers? And you are not specifying authSource for correct authenticationSound
C
-2

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.

Cleavable answered 22/1, 2022 at 21:0 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.