MongoDB by default doesn’t provide any authentication mechanism and therefore it is required to activate one by tweaking the configuration file and issuing some commands in the mongodb. Today I will show you how to activate authentication on MongoDB.
Create a folder for holding up the key
mkdir /mongodb-security
chown mongodb /mongodb-security
chgrp mongodb /mongodb-security
Generate a new key inside the folder
cd /mongodb-security
openssl rand -base64 741 > mongo.key
chown mongodb /mongodb-security/mongo.key
chgrp mongodb /mongodb-security/mongo.key
chmod 700 /mongodb-security/mongo.key
Edit /etc/mongodb.conf
Add the following line to the configuration line
keyFile = /mongodb-security/mongo.key
Restart the server
sudo service mongod restart
Create Users
Issue the following on the terminal
mongo
use admin
db.createUser( { user: "admin", pwd: "password", roles: ["userAdminAnyDatabase"] } ) exitmongo -u admin -p password --authenticationDatabase admindb.createUser( { user: "root", pwd: "123456", roles: [ "root" ] } )exit
Connecting to MongoDB
Now you have activated the user authentication and in order to connect to the database you need to issue the following command
mongo -u root -p 123456 --authenticationDatabase admin