...

MongoDB Auth Setup: A 10-Step Easy Guide to Secure Database

Rate this post

Introduction

MongoDB Auth Setup involves securing the database cluster by implementing user authentication and authorization mechanisms. Authentication enhances MongoDB’s security by requiring valid credentials for access, significantly reducing the risk of unauthorized access or data breaches.

MongoDB auth setup involves several key steps are involved. These include creating administrative users with appropriate privileges, enabling authentication in the MongoDB configuration, and ensuring the proper configuration replication across all replica set members.

Implementing authentication in a running replica set enhances data security, safeguarding sensitive information stored within the database. This introductory process guides administrators through the essential procedures needed to fortify MongoDB replica sets, ensuring secure access and bolstering the overall integrity of the database cluster.

Prerequisites for MongoDB Auth Setup

Setting up auth in Mongo replicaset secures our replicaset members using internal auth and client applications using username and password auth.

No Auth to auth transition during MongoDB Auth Setup

MongoDB Auth Setup in Running Replica Set
MongoDB Auth Setup in Running Replica Set

Without auth setup, /etc/mongod.conf will be similar to the below file.

# mongod.conf

# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/

# Where and how to store data.
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true
#  engine:
#  mmapv1:
#  wiredTiger:

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

# network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1,10.129.0.2

# how the process runs
processManagement:
  timeZoneInfo: /usr/share/zoneinfo

#security:

#operationProfiling:

replication:
        replSetName: rs1

Transition State

mongod running with –transitionToAuth accepts both authenticated and non-authenticated connections. Clients connected to the mongod during this transition state can perform read, write, and administrative operations on any database.

Major Steps in MongoDB Auth Setup in a Running Replicaset

MongoDB Auth Setup in a Running Replicaset
MongoDB Auth Setup in a Running Replicaset

Step 1 – Create the user admin

Connect to the primary to create a user with userAdminAnyDatabase role. The userAdminAnyDatabase role grants access to user creation on any database in the deployment.

admin = db.getSiblingDB("admin")
admin.createUser(
  {
    user: "admin",
    pwd: "gknsnskn1234",     // or cleartext password
    roles: [ { role: "userAdminAnyDatabase", db: "admin" }]
  }
)

Step 2 – Create the cluster administrator role

Connect to the primary to create a user with clusterAdmin role. The clusterAdmin role grants access to replication operations, such as configuring the replica set.

db.getSiblingDB("admin").createUser(
  {
    "user" : "clusterAdmin",
    "pwd" :  "kskhnfjiw3214",     // or cleartext password
    roles: [ { "role" : "clusterAdmin", "db" : "admin" } ] 
  }
)

Step 3 – Create users for the client application

db.getSiblingDB("admin").createUser(
  {
    "user" : "mainuser",
    "pwd" :  "ksnknsknnksnk1234",
    roles: [ { "role" : "readWrite", "db" : "school" } ] 
  }
)

Step 4 – Update Client Applications

mongo  -u mainuser -password  -authenticationDatabase admin --host rs1/10.129.0.2:27017,10.129.0.3:27017,10.129.0.4:27017

Note: update mongo username and password in your backend application as well.

Step 5 – Create keyFile

openssl rand -base64 100 > mongodb_internal_key # generate a random string of 100 bytes and write into mongodb_internal_key
#Sample cotents of mongodb_internal_key is as below
bm0PnrmJrbxsHM76sGAGUg5BtO50oqGQ4rR8mD5EhTvtL0blQywdtTJG+kyZH5bx
/PvhL9MG/C66Bt1NQO+e6WV58FLqy9jqEPb9AoT3fgbA+eIncERIFsBgotsLnbq0
4dsf5g==

Step 6 – Copy the keyFile to each replica set member

Copy the keyfile to each server hosting the replica set members. Ensure that the user running the mongod instances is the owner of the file and can access the keyfile. File permission should be 400.

chmod 400 mongodb_internal_key
sudo chown mongodb:mongodb mongodb_internal_key
sudo mv mongodb_internal_key /etc

Step 7 – Restart each secondary or arbiter member of the replica set with transitionToAuth.

Restart the secondary or arbiter one at a time.

# Stop mongod service
admin = db.getSiblingDB("admin")
admin.shutdownServer()

# update security as below in /etc/mongod.conf, save the file
security:
  authorization: enabled
  keyFile: /etc/mongodb_internal_key
  transitionToAuth: true

# Start mongod service
sudo systemctl start mongod

Step 8 – Step down the primary member of the replica set and restart it with –transitionToAuth

# Increase priority of any secondary first and update conf
Understand with below example when members[0] is primary and has priority=4 and members[1].priority = 3
Login to mongo shell
conf=rs.conf()
conf.members[1].priority=5
rs.reconfig(conf)
# members[1] will become primary after above operation

# Stop mongod
rs.stepDown()
admin = db.getSiblingDB("admin")
admin.shutdownServer()

# update security as below in /etc/mongod.conf, mongodb_internal_key must be created as instructed in step 6
security:
  authorization: enabled
  keyFile: /etc/mongodb_internal_key
  transitionToAuth: true

# Start mongod service
sudo systemctl start mongod

Step 9 – Restart secondaries and arbiters without –transitionToAuth

# Stop mongod
admin = db.getSiblingDB("admin")
admin.shutdownServer()

# update security as below in /etc/mongod.conf
security:
  authorization: enabled
  keyFile: /etc/mongodb_internal_key

# Start mongod service
sudo systemctl start mongod

And set rs.slaveOk() or rs.secondaryOK() (for newer versions 5 and later)

Step 10 – Step down and restart the primary replica set member without –transitionToAuth

# Increase priority of any secondary first and update conf
# Understand with below example when members[1] is primary and has priority=5 and members[0].priority = 4
# Login to mongo shell
conf=rs.conf()
conf.members[0].priority=6
rs.reconfig(conf)
# members[0] will become primary after above operation

# Stop mongod
rs.stepDown()
admin = db.getSiblingDB("admin")
admin.shutdownServer()

# update security as below in /etc/mongod.conf, mongodb_internal_key must be created as instructed in step 6
security:
  enabled: true
  keyFile: /etc/mongodb_internal_key

# Start mongod service
sudo systemctl start mongod

With auth setup, the final version of /etc/mongod.conf would be as below

# mongod.conf

# for documentation of all options, see:
#   http://docs.mongodb.org/manual/reference/configuration-options/

# Where and how to store data.
storage:
  dbPath: /var/lib/mongodb
  journal:
    enabled: true
#  engine:
#  mmapv1:
#  wiredTiger:

# where to write logging data.
systemLog:
  destination: file
  logAppend: true
  path: /var/log/mongodb/mongod.log

# network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1,10.129.0.2

# how the process runs
processManagement:
  timeZoneInfo: /usr/share/zoneinfo

security:
  authorization: enabled
  keyFile: /etc/mongodb_internal_key

#operationProfiling:

replication:
        replSetName: rs1

Validation of mongoDB Auth Setup: ReplicaSet operation will require auth after enabling authentication.

# Login to mongo shell (mongo or mongosh)
db.getSiblingDB('admin').auth('clusterAdmin', 'kskhnfjiw3214')
rs.slaveOk()
rs.conf()

Conclusion

MongoDB auth setup is pivotal for safeguarding data integrity. In conclusion, the mongoDB auth setup process involves configuring user authentication across all nodes within the replica set. By creating administrative users and establishing role-based access control (RBAC), MongoDB ensures secure access to databases.

MongoDB auth setup requires members of the replicaset to provide internal authentication to include it as a member of the replicaset.

Leveraging authentication mechanisms such as SCRAM (Salted Challenge Response Authentication Mechanism) adds an extra layer of protection against unauthorized access. It’s imperative to periodically review user access privileges and regularly update passwords to maintain security protocols. This robust authentication setup not only fortifies data confidentiality but also bolsters the integrity of the entire MongoDB Replica Set.

Implementing and maintaining proper authentication measures remains essential for safeguarding sensitive data and ensuring compliance with security best practices.

Enjoy the post!

Related Posts

Monitor MongoDB with MongoDB Exporter

Spread the love

Leave a Comment

Seraphinite AcceleratorOptimized by Seraphinite Accelerator
Turns on site high speed to be attractive for people and search engines.