Tuesday, August 23, 2016

Enabling client authentication in MongoDB

Before enabling authentication in MongoDB, we'll have to create a user and assign it a built-in role. We'll use the built-in "root" role that provides admin access to all databases.

I've done this in Ubuntu using MongoDB 3.2.



Issue the following commands to create a new user in the "admin" database:

use admin
db.createUser({
    user: "admin",
    pwd: "password",
    roles: [
        { role: "root", db: "admin" }
    ]
})

You can assign more roles to a user. But we're keeping it simple. Full documentation for the createUser() function available here.

Once that's done, open the file /etc/mongodb.conf. Look for the following line and uncomment it:

auth = true

Restart your MongoDB instance.

You can still connect to MongoDB without specifying username/password. But you won't be able to execute anything.

$ mongo
MongoDB shell version: 3.2.9
connecting to: test
> db.getCollectionNames()
2016-08-23T14:07:41.398+0800 E QUERY    [thread1] Error: listCollections failed: {
        "ok" : 0,
        "errmsg" : "not authorized on test to execute command { listCollections: 1.0, filter: {} }",
        "code" : 13
} :
_getErrorWithCode@src/mongo/shell/utils.js:25:13
DB.prototype._getCollectionInfosCommand@src/mongo/shell/db.js:773:1
DB.prototype.getCollectionInfos@src/mongo/shell/db.js:785:19
DB.prototype.getCollectionNames@src/mongo/shell/db.js:796:16
@(shell):1:1

You'll need to specify additional parameters to connect since we've authentication enabled:

$ mongo -u admin -p password --authenticationDatabase admin
MongoDB shell version: 3.2.9
connecting to: test
> db.getCollectionNames()
[ ]
> 

1 comment:

vinu priya said...

This information is impressive; I am inspired with your post writing style & how continuously you describe this topic. After reading your post, thanks for taking the time to discuss this, I feel happy about it and I love learning more about this topic. Android App Development Company in India