How to Enable auth using MONGODB-CR in MongoDB?

Connect with

enable auth using mongodb-crHow to enable auth using mongodb-cr in MongoDB upto 2.6 version, enabling of username/password is simple or you can say authentication and authorization in mongoDB 2.6 or lesser version of mongodb < 3.0 using MONGODB-CR is very simple.

Follow the following steps and you are done with adding role based security in mongodb.

Note: MONGODB-CR authentication and authorization mechanism is only supported in lesser version of mongoDB 3.0 , it means lesser or equal to mongoDB 2.6.

If you have installed 3.0 or higher read our another post how to enable authentication and authorization of user using SCRAM-SHA-1 security mechanism.

1. Pre-requisite to enable auth using MONGODB-CR

Following things need to be in place in order to enable authentication and authorization by using MONGODB-CR mechanism. I mean to say, enabling of user security in mongoDB by using MONGODB-CR is simple and for this follow following steps.

– MongoDB 2.6 version must be installed. in my case, I have tested with MongoDB 2.6, Linux CentOS 6.5.

Check mongoDB version

 
mongo -version

output:

MongoDB shell version: 2.6

2. Add security line in config file

Add following line in /etc/mongod.config file, if not already added in MongoDB 2.6 or lower version.

 
auth=true

sameple /etc/mongod.config
Following is the sample of mongoDB file ( this is not YAML which latest version by default have) , although mongodb 2.6 support yaml format.

 
# mongod.conf
#where to log
logpath=/var/log/mongodb/mongod.log
logappend=true
# fork and run in background
fork=true
#port=27017
dbpath=/var/lib/mongo
# location of pidfile
pidfilepath=/var/run/mongodb/mongod.pid
# Listen to local interface only. Comment out to listen on all interfaces.
#bind_ip=127.0.0.1

# Disables write-ahead journaling
# nojournal=true

# Enables periodic logging of CPU utilization and I/O wait
#cpu=true

# Turn on/off security.  Off is currently the default
#noauth=true
auth=true

# Verbose logging output.
#verbose=true

# Inspect all client data for validity on receipt (useful for
# developing drivers)
#objcheck=true

# Enable db quota management
#quota=true

# Set oplogging level where n is
#   0=off (default)
#   1=W
#   2=R
#   3=both
#   7=W+some reads
#diaglog=0

# Ignore query hints
#nohints=true

# Enable the HTTP interface (Defaults to port 28017).
#httpinterface=true

# Turns off server-side scripting.  This will result in greatly limited
# functionality
#noscripting=true

# Turns off table scans.  Any query that would do a table scan fails.
#notablescan=true

# Disable data file preallocation.
#noprealloc=true

# Specify .ns file size for new databases.
# nssize=

# Replication Options

# in replicated mongo databases, specify the replica set name here
#replSet=rs1

# maximum size in megabytes for replication operation log
#oplogSize=1024
# path to a key file storing authentication info for connections
# between replica set members
#keyFile=/path/to/keyfile

3. Login into mongo shell

 
mongo

4. Add Username and Password to Enable Security

Before adding user user to db , switch to admin db and then add user(s) to admin database.
switched to db admin and created a root i.e. super user of mongodb.

> use admin
switched to db admin
> db.createUser({ user: "mysoftkey",  pwd: "xxxxx", roles: ["root"]});

5. Authenticate via username and password

Follow any one of the following steps.
if you are already logged-in in mongo type following to authenticate else do following ‘OR’ step

 mongo --username "mysoftkey" --password "xxxxx" --authenticationDatabase "admin"

Output:
There are some warning which can be ignored while adding user and role based security in mongoDB.

[root@localhost ~]# mongo --username "mysoftkey" --password "xxxxx" --authenticationDatabase "admin"
MongoDB shell version: 2.6
connecting to: test
Server has startup warnings:
2016-11-10T17:40:44.667+0530 I CONTROL  [initandlisten]
2016-11-10T17:40:44.667+0530 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/enabled is 'always'.
2016-11-10T17:40:44.667+0530 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2016-11-10T17:40:44.667+0530 I CONTROL  [initandlisten]
2016-11-10T17:40:44.667+0530 I CONTROL  [initandlisten] ** WARNING: /sys/kernel/mm/transparent_hugepage/defrag is 'always'.
2016-11-10T17:40:44.667+0530 I CONTROL  [initandlisten] **        We suggest setting it to 'never'
2016-11-10T17:40:44.667+0530 I CONTROL  [initandlisten]
2016-11-10T17:40:44.667+0530 I CONTROL  [initandlisten] ** WARNING: soft rlimits too low. rlimits set to 1024 processes, 64000 files. Number of processes should be at least 32000 : 0.5 times number of files.
2016-11-10T17:40:44.667+0530 I CONTROL  [initandlisten]
> show dbs;
admin  0.000GB
local  0.000GB
mydb   0.000GB
>

6. Login by username and password

Follow any one of the following steps.

Output as follows for show dbs command, if successfully not authenticated

> show dbs;
2016-11-10T17:40:55.437+0530 E QUERY    [thread1] Error: listDatabases failed:{
        "ok" : 0,
        "errmsg" : "not authorized on admin to execute command { listDatabases: 1.0 }",
        "code" : 13
} :
_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

After successfully login following like output will display , containing dbname and its content size in GB.

> show dbs;
admin  0.000GB
local  0.007GB

7. Output of console to enable Auth

Following are the complete console output for all the activities to enable authentication and authorization using MONGODB-CR mechanism in mongoDB 2.6.

[root@ranjeet ~]# vim /etc/mongod.conf
[root@ranjeet ~]# service mongod restart
Stopping mongod:                                           [  OK  ]
Starting mongod:                                           [  OK  ]
[root@ranjeet ~]# mongo
MongoDB shell version: 2.6
connecting to: test
> use admin
switched to db admin

> show dbs;
2016-11-10T17:40:55.437+0530 E QUERY    [thread1] Error: listDatabases failed:{
        "ok" : 0,
        "errmsg" : "not authorized on admin to execute command { listDatabases: 1.0 }",
        "code" : 13
} :
_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

> db.createUser({ user: "ranjeet",  pwd: "xxxxx", roles: ["root"]});
Successfully added user: { "user" : "ranjeet", "roles" : [ "root" ] }
> db.auth('ranjeet', 'xxxxx' )
1
> show dbs;
admin  0.000GB
local  0.007GB
>
> use mydb;
switched to db mydb
> db.mycollection.insert({"name":"mysoftkey", "description":"How to enable security using MONGODB-CR auth mechanism"});
WriteResult({ "nInserted" : 1 })
> db.mycollection.find();
{ "_id" : ObjectId("582467543f20f886e3a54a25"), "name" : "meenu", "description" : "enabling auth security using MONGODB-CR mechanism" }
>

After successful login it return 1 in db.auth('mysoftkey', 'xxxxx') and once you type 'show dbs;' it returns all the database name with content size in gb.

8. Reference

https://docs.mongodb.com/v3.2/core/security-mongodb-cr/
You can also visit MongoDB Tutorial Listing page for more articles on MongoDB document-oriented database.
Happy Learning! 🙂


Connect with

Leave a Comment

Your email address will not be published. Required fields are marked *