step 1

start mongodb without access control

# /opt/mongodb/bin/mongod --fork --logpath /var/log/config_mongo.log --configsvr --logappend --dbpath /home/data/config/ --port 1000
# /opt/mongodb/bin/mongod --fork --logpath /var/log/mongodb.log --logappend --dbpath /home/data/node1 --port 100
# /opt/mongodb/bin/mongod --fork --logpath /var/log/mongodb2.log --logappend --dbpath /home/data/node2 --port 200
# /opt/mongodb/bin/mongod --fork --logpath /var/log/mongodb3.log --logappend --dbpath /home/data/node3 --port 300
# /opt/mongodb/bin/mongos --configdb 10.128.10.58:1000 --logappend --fork --logpath /var/log/mongos.log --port 27017

step 2

then login to mongos and create database admin to manage all database on the server

# /opt/mongodb/bin/mongo (using standard port 27017)

MongoDB shell version: 3.2.3
connecting to: test
mongos> use admin
db.createUser(
  {
    user: "usrAdmin",
    pwd: "AdminP4ssw0rd",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" },{ role: "clusterAdmin", db: "admin" }, { role: "readWriteAnyDatabase", db: "admin" }, { role: "dbAdminAnyDatabase", db: "admin" }, { role: "readWriteAnyDatabase", db: "admin" }  ]
  }
)

step 3

create KeyFile for auth mongodb

# touch /home/data/source/KeyFile
# chmod 600 /home/data/source/KeyFile
# vi /home/data/source/KeyFile (isi sesuai password)

step 4

stop each instans of mongodb

# killal -9 mongod (or mongos) 

step 5

start each instance mongodb with option –keyFile /home/data/source/KeyFile

# /opt/mongodb/bin/mongod --fork --logpath /var/log/config_mongo.log --configsvr --logappend --dbpath /home/data/config/ --port 1000 --keyFile /home/data/source/KeyFile
# /opt/mongodb/bin/mongod --fork --logpath /var/log/mongodb.log --logappend --dbpath /home/data/node1 --port 100 --keyFile /home/data/source/KeyFile
# /opt/mongodb/bin/mongod --fork --logpath /var/log/mongodb2.log --logappend --dbpath /home/data/node2 --port 200 --keyFile /home/data/source/KeyFile
# /opt/mongodb/bin/mongod --fork --logpath /var/log/mongodb3.log --logappend --dbpath /home/data/node3 --port 300 --keyFile /home/data/source/KeyFile
# /opt/mongodb/bin/mongos --configdb 10.128.10.58:1000 --logappend --fork --logpath /var/log/mongos.log --port 27017 --keyFile /home/data/source/KeyFile

step 6

login to mongos server

# /opt/mongodb/bin/mongo 

MongoDB shell version: 3.2.3
connecting to: test
mongos> use admin
switched to db admin
mongos> db.auth("usrAdmin","AdminP4ssw0rd")
1
mongos>

when you success login to mongodb with user and pass you’re created, so auth is enable.

hope this article help you, thank you

Advertisements