Follow by Email

Adding user authentication on MongoDB replica set

Stoping the MongoDB replication -
* Note : Assuming  dbe1 as primary, dbe2 as secondary, dbe3 as secondary, dbw1 as hidden
a] Go to mongo shell-
Stop the secondaries first using below commands:
 
use admin
db.shutdownServer()
b] Go to Linux shell-
sudo service mongod stop
C] Go to primary server dbe1 first and then secondaries and follow below steps:
1) Config file path : /etc/mongod.conf
     a) security :
            authorize : enabled
     b) bindIp: 127.0.0.1 (backend server's IP) 
*Note : It will allow only this provided ip to connect the MongoDB server.
     c) Restart your mongodb service
          command : sudo service mongod restart
*Note : Assuming "database1" is your database name, "user1" is your user name, "admin123" is your password
2) go to mongo shell and type below command :
   a) use database1
   b) db.createUser(
     {
        user: "user1",
        pwd: "admin123",
        roles: [ { role: "root", db: "database1" } ]
     }
    )
3) Exit from the command prompt and try connecting using below command on the mongo shell:
mongo --port 27017 -u "user1" -p "admin123" --authenticationDatabase "database1"
* Go to primary and type below command
1] rs.initiate()
2] rs.add("dbe2:27023")
3] rs.add("dbe3:27024")
4] rs.add({ "_id" : 3, "host" : "dbw1:27025", "priority" : 0, "hidden" : true })
5] rs.status()