How to Setup Authentication for Connections on MongoDB

mongodb

How to configure authentication for MongoDB when using mongo Shell or any other sort of client?

Best Answer

Here is a complete solution, including creation of a "super user", capable to access any resources and perform any operation.


Notice

  • First: the first access to MongoDB is made without authentication ($ mongo).

  • Second: the configuration file of MongoDB may differ, depending on which version are you using (3.x: mongod.conf / 2.x: mongodb.conf)


Creating User

> use admin
switched to db admin
> db.createUser( {user:"mongo", pwd:"mongo", roles:["root"]} )
Successfully added user: { "user" : "mongo", "roles" : [ "root" ] }

Verifying User Creation and Authentication

> db.getUser("mongo")
{
    "_id" : "admin.mongo",
    "user" : "mongo",
    "db" : "admin",
    "roles" : [
        {
            "role" : "root",
            "db" : "admin"
        }
    ]
}

> db.auth("mongo","mongo")
1

Enabling Authentication

check which config file is using MongoDB

$ ps aux | grep mongo
mongodb  12583  0.5  3.4 2381948 281140 ?  Sl  18:34  0:06 /usr/bin/mongod --config /etc/mongod.conf

MongoDB 3.x

$ grep -A 1 security /etc/mongod.conf 
security:
   authorization: enabled

MongoDB 2.x

$ grep -B 2 auth=True /etc/mongodb.conf
# Turn on/off security.  Off is currently the default
#noauth = true
auth=True

Restart MongoDB (SysV script)

$ /etc/init.d/mongodb restart

Connecting via Mongo Shell

$ mongo -u mongo -p --authenticationDatabase admin
MongoDB shell version v3.4.3
Enter password: ********** 
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.3
> show dbs
admin     0.078GB
android   0.078GB
blog      0.078GB
games     0.078GB
school    0.078GB

Notice: you can just hit mongo and open the Mongo Shell, but it will not let you perform any action, due to the fact that you were not previously authenticated.

$ mongo
MongoDB shell version v3.4.3
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.3
> show dbs
2017-10-03T19:04:55.953+0000 E QUERY    [thread1] Error: listDatabases failed:{
"ok" : 0,
"errmsg" : "not authorized on admin to execute command { listDatabases: 1.0 }",
"code" : 13,
"codeName" : "Unauthorized"
} :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
Mongo.prototype.getDBs@src/mongo/shell/mongo.js:62:1
shellHelper.show@src/mongo/shell/utils.js:761:19
shellHelper@src/mongo/shell/utils.js:651:15
@(shellhelp2):1:1
> 

For dropping a user:

> use admin
> db.dropUser("myuser")

References: