Configuring Authentication and Users - Mongo DB

Overview

This article explains how to configure authentication and setup users for a Mongo DB instance.

Procedure

On the Primary Server

1. Turn off replication

mongo

For each host name within the replica set, within the Mongo shell issue the following command.

rs.remove("host-name:27017")

2. Add root user (still in the Mongo shell)

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

3. Create additional users (still in the Mongo shell)

db.createUser({user:"MyUserName", pwd:"MySecurePassword",
roles:[ 
   {role:"readWrite",db:"MyDatabase1"},
   . . .
   {role:"readWrite",db:"MyDatabaseN"}
   ]})

4. Shutdown the database (still within the Mongo shell)

db.shutdownServer({force:true})
exit

After this step, you should be back at the Linux prompt

5. Create the authorization key file.

openssl rand -base64 755 > /mongo/keys/mongod-auth.key

All Mongo DB Servers

1. If necessary, stop the Mongo DB service

service mongod stop

2. Configure authorization in the /etc/mongod.conf file by adding the following lines to the "security:" section

  authorization: enabled
  keyFile: /mongo/keys/mongod-auth.key

3. Verify the above change

cat /etc/mongod.conf | grep "authorization"

4. Install the authorization key file (all servers except Primary)

IMPORTANT: The mongod-auth.key must have the same contents on all Mongo DB Servers! Copy the /mongo/keys/mongod-auth.key file from the Primary server to the same folder on all the other servers.

5. Adjust security on the authorization key file.

chown mongod:mongod /mongo/keys/mongod-auth.key
chmod 400 /mongo/keys/mongod-auth.key
cat /mongo/keys/mongod-auth.key

Primary Server

1. Exit from the Mongo DB shell (if necessary)

2. Log into Mongo as the root user

mongo -u root admin -p

At the prompt, provide the password for the root user.

3. Re-activate replication (within the Mongo DB shell)

For each server in the replica set

rs.add("host-name:27017")

4. Exit the Mongo DB shell.

5. Start the Mongo DB service

service mongod start