112

I've created an admin user for mongo using these directions:

http://docs.mongodb.org/manual/tutorial/add-user-administrator/

From the mongo client it looks like I can authenticate:

> use admin
switched to db admin
> db.auth('admin','SECRETPASSWORD');
1
>

But I can't connect any other way. For example:

mongo -u admin -p SECRETPASSWORD

gives the error:

JavaScript execution failed: Error: 18 { code: 18, ok: 0.0, errmsg: "auth fails" } at src/mongo/shell/db.js:L228

I have auth = true in etc/mongod.conf.

What am I missing?

Sampada
  • 2,931
  • 7
  • 27
  • 39
justkevin
  • 3,089
  • 3
  • 28
  • 33
  • 1
    Maybe Mongo is configured to only accept connections from localhost? That at least happened to me using our production mongodb instance when trying to access it from my computer. – Akku Aug 13 '13 at 18:51
  • I don't think so, I get that error message when connecting from the same machine as mongod. Also, it lets me connect without supplying a username/password and then supplying a username/password with db.auth (my first example). – justkevin Aug 13 '13 at 18:58
  • PS: [`db.changeUserPassword("admin", "password")`](http://docs.mongodb.org/manual/tutorial/change-user-password/) to change password for each databases. – laggingreflex Apr 13 '15 at 02:32
  • Might help https://stackoverflow.com/questions/47253584/authenticate-after-picking-the-database – DaveIdito Sep 06 '19 at 11:45

14 Answers14

130

Authentication is managed at a database level. When you try to connect to the system using a database, mongo actually checks for the credentials you provide in the collection <database>.system.users. So, basically when you are trying to connect to "test", it looks for the credentials in test.system.users and returns an error because it cannot find them (as they are stored in admin.system.users). Having the right to read and write from all db doesn't mean you can directly connect to them.

You have to connect to the database holding the credentials first. Try:

mongo admin -u admin -p SECRETPASSWORD

For more info, check this http://docs.mongodb.org/manual/reference/privilege-documents/

johntellsall
  • 14,394
  • 4
  • 46
  • 40
gilo
  • 1,309
  • 1
  • 8
  • 3
  • 7
    as is also mentioned below, in another answer (but I missed it, since I only looked at the top voted ones) i needed to add **single quotes** around username and password, before i could login – gsaslis Nov 21 '16 at 07:34
  • 2
    Yes, if you use double quotes, idiotic bash will possibly do all kinds of nasty things. – moodboom Jan 23 '20 at 19:45
95

I also received this error, what I needed was to specify the database where the user authentication data was stored:

mongo -u admin -p SECRETPASSWORD --authenticationDatabase admin

Update Nov 18 2017:

mongo admin -u admin -p

is a better solution. Mongo will prompt you for your password, this way you won't put your cleartext password into the shell history which is just terrible security practice.

Sampada
  • 2,931
  • 7
  • 27
  • 39
Chad E.
  • 1,196
  • 9
  • 12
  • 3
    Yes, this answer works! Combining this with the answer from @gilo, the following command works for me: "mongo MYDB -u admin -p SECRETPASSWORD --authenticationDatabase admin" – Tsung-Ting Kuo May 06 '16 at 21:46
41

You may need to upgrade your mongo shell. I had version 2.4.9 of the mongo shell locally, and I got this error trying to connect to a mongo 3 database. Upgrading the shell version to 3 solved the problem.

lmyers
  • 2,654
  • 1
  • 24
  • 22
  • 7
    As stated in the doc:Versions of the mongo shell before 3.0 are not compatible with 3.0 deployments of MongoDB that enforce access control. If you have a 3.0 MongoDB deployment that requires access control, you must use 3.0 versions of the mongo shell. – Finch_Powers Aug 27 '15 at 13:48
35

I know this may seem obvious but I also had to use a single quote around the u/n and p/w before it worked

mongo admin -u 'user' -p 'password'

Sampada
  • 2,931
  • 7
  • 27
  • 39
user3609666
  • 351
  • 3
  • 2
22

In MongoDB 3.0, it now supports multiple authentication mechanisms.

  1. MongoDB Challenge and Response (SCRAM-SHA-1) - default in 3.0
  2. MongoDB Challenge and Response (MONGODB-CR) - previous default (< 3.0)

If you started with a new 3.0 database with new users created, they would have been created using SCRAM-SHA-1.

So you will need a driver capable of that authentication:

http://docs.mongodb.org/manual/release-notes/3.0-scram/#considerations-scram-sha-1-drivers

If you had a database upgraded from 2.x with existing user data, they would still be using MONGODB-CR, and the user authentication database would have to be upgraded:

http://docs.mongodb.org/manual/release-notes/3.0-scram/#upgrade-mongodb-cr-to-scram

Now, connecting to MongoDB 3.0 with users created with SCRAM-SHA-1 are required to specify the authentication database (via command line mongo client), and using other mechanisms if using a driver.

$> mongo -u USER -p PASSWORD --authenticationDatabase admin

In this case, the "admin" database, which is also the default will be used to authenticate.

Lee Parayno
  • 396
  • 3
  • 7
  • This change in behavior is important, as it tripped me up when mixing a new version of MongoDB and an old version of pymongo. You need to ensure your mongo instance and all mongo clients are up to date. – i_grok Mar 15 '16 at 00:43
  • This was my case: 1. Changed mongo-java-driver-2.12.3.jar to mongo-java-driver-3.2.2.jar 2. Changed MongoCredential.createMongoCRCredential to MongoCredential.createCredential – nikolai.serdiuk Apr 12 '16 at 06:15
  • ugh. how hard would it be for the developers to give us a better error like "invalid authentication method" – Byron Whitlock Dec 20 '16 at 16:51
21

This fixed my issue:

Go to terminal shell and type mongo.

Then type use db_name.

Then type:

 db.createUser(
   {
     user: "mongodb",
     pwd: "dogmeatsubparflavour1337",
     roles: [ { role: "dbOwner", db: "db_name" } ]
   }
 )

Also try: db.getUsers()

Quick sample:

const MongoClient = require('mongodb').MongoClient;

// MongoDB Connection Info
const url = 'mongodb://mongodb:dogmeatsubparflavour1337@stackoverflow.com:27017/?authMechanism=DEFAULT&authSource=db_name';
// Additional options: https://docs.mongodb.com/manual/reference/connection-string/#connection-string-options

// Use Connect Method to connect to the Server
MongoClient.connect(url)
  .then((db) => {
    console.log(db);
    console.log('Casually connected correctly to server.');
    // Be careful with db.close() when working asynchronously
    db.close();
  })
  .catch((error) => {
    console.log(error);
  });
agm1984
  • 15,500
  • 6
  • 89
  • 113
  • 2
    To add: 1. Login to admin database with mongodb superadmin first: ```mongo 'mongodb://localhost:27017/admin' -u admin -p``` 2. Then switch to the target database: ```> use targetDb``` 3. Then add the user ```> db.createUser(...)``` – daniel.widyanto Jan 19 '18 at 10:41
14

It appears the problem is that a user created via the method described in the mongo docs does not have permission to connect to the default database (test), even if that user was created with the "userAdminAnyDatabase" and "dbAdminAnyDatabase" roles.

justkevin
  • 3,089
  • 3
  • 28
  • 33
4

Another possibility: When you created the user, you may have accidentally been useing a database other than admin, or other than the one you wanted. You need to set --authenticationDatabase to the database that the user was actually created under.

mongodb seems to put you in the test database by default when you open the shell, so you'd need to write --authenticationDatabase test rather than --authenticationDatabase admin if you accidentally were useing test when you ran db.createUser(...).

Assuming you have access to the machine that's running the mongodb instance, y could disable authorization in /etc/mongod.conf (comment out authorization which is nested under security), and then restart your server, and then run:

mongo
show users

And you might get something like this:

{
    "_id" : "test.myusername",
    "user" : "myusername",
    "db" : "test",
    "roles" : [
        {
            "role" : "dbOwner",
            "db" : "mydatabasename"
        }
    ],
    "mechanisms" : [
        "SCRAM-SHA-1",
        "SCRAM-SHA-256"
    ]
}

Notice that the db value equals test. That's because when I created the user, I didn't first run use admin or use desiredDatabaseName. So you can delete the user with db.dropUser("myusername") and then create another user under your desired database like so:

use desiredDatabaseName
db.createUser(...)

Hopefully that helps someone who was in my position as a noob with this stuff.

  • Thank you for reminding me of the standard database "test". That was so helpful because mongodb closes the gates when the first user has been created. – Holger Schmeken Apr 08 '21 at 21:24
3

You can also try this :-

mongo localhost:27017/admin -u admin -p SECRETPASSWORD

Found it in this post

Here obviously the localhost can be some other host and the /admin can be some other database on which authentication has been applied

Community
  • 1
  • 1
Kelsnare
  • 635
  • 5
  • 12
2

This is kind of a specific case, but in case anyone gets here with my problem:

In MongoHQ, it'll show you a field called "password", but it's actually just the hash of the password. You'll have to add a new user and store the password elsewhere (because MongoHQ won't show it to you).

maxko87
  • 2,892
  • 4
  • 28
  • 43
2

The proper way to login into mongo shell is

mongo localhost:27017 -u 'uuuuu' -p '>xxxxxx' --authenticationDatabase dbname

Moh .S
  • 1,920
  • 19
  • 19
1
mongo admin -u root -p root

mongorestore -u root  --authenticationDatabase admin --db rtp_new mongo
EstevaoLuis
  • 2,422
  • 7
  • 33
  • 40
0

Check for the mongo version of the client from where we are connecting to mongo server.

My case, mongo server was of version Mongo4.0.0 but my client was of version 2.4.9. Update the mongo version to update mongo cli.

Sandy
  • 946
  • 11
  • 14
0

I was getting this error because I was forgetting to remove the angled brackets in the <password> of the mongoURI. Removing them worked like a charm.