Once MongoDB is installed, by default, authentication is not enabled, users can login without specifying user name / password. Authorization is extremely important for security and needs to be enabled.
The following steps must be followed in order for enabling authorization (Server Centos Linux 7, MongoDB version 3.2):
You may also want to read the below article.
“Deploy Sharded Cluster with Keyfile Access Control on Red Hat Enterprise Linux or CentOS Linux”
Step 1: Create a Key File for Enabling Authorization
First, a key file is created with openssl. This file will be used for connection and communication between servers.
1 2 3 4 | [mongodb@mongodb1 ~]$ cd /mongodb [mongodb@mongodb1 ~]$ mkdir keyfile [mongodb@mongodb1 ~]$ openssl rand -base64 346 > keyfile/mongodb-keyfile [mongodb@mongodb1 ~]$ chmod 600 keyfile/mongodb-keyfile |
Step 2: Copy Key File To Other Servers
This created file is copied to the corresponding directory of all servers. The key file on all servers must be the same.
Step 3: Restart Mongod and Mongos with Parameters
All mongod and mongos operations are restarted using this keyfile. The commands are given the parameter –keyfile <file_path>. Below are sample commands for example mongod (config, shard) and mongos (router) operations.
1 2 3 4 | [mongodb@mongodb1 ~]$ mongod --configsvr --dbpath cfg0 --port 26001 --fork --logpath logs/log.cfg0 --logappend --keyFile keyfile/mongodb-keyfile [mongodb@mongodb1 ~]$ mongod --shardsvr --replSet shA --dbpath shA0 --logpath logs/log.shA0 --port 27500 --fork --logappend --keyFile keyfile/mongodb-keyfile [mongodb@mongodb1 ~]$ mongos --configdb mongodb1:26001,mongodb2:26001,mongodb3:26001 --fork --logappend --logpath logs/log.mongos0 --keyFile keyfile/mongodb-keyfile |
Step 4: Create Administration Account
The next step in enabling authorization is to create an administrator account.
1 2 3 4 5 6 7 8 9 10 11 12 | [mongodb@mongodb1 ~]$ mongo mongos> use admin mongos> db.createUser( { user: "adminUser", pwd: "password", roles: [ { role: "userAdminAnyDatabase", db: "admin" }, { role: "readWriteAnyDatabase", db: "admin" }, { role: "dbAdminAnyDatabase", db:"admin" }, { role: "clusterAdmin", db:"admin" } ] } ) |
Step 6: Check Status of the Account
The status of the user can be seen with the following command.
1 | mongos> db.getUser("adminUser") |
Step 7: Check MongoDB Authorization
The next mongos login requires authorization, otherwise you will get an error.
1 | [mongodb@mongodb1 ~]$ mongo --port 27017 -u adminUser -p Password --authenticationDatabase admin |