How to secure MongoDB databases

Date: 22-12-2020

You must edit mongod.conf, MongoDB’s configuration file to enable authentication. Once you enabled it and restart the Mongo service, users will still be able to connect to the database without authenticating. However, they won’t be able to read or modify any data until they provide a correct username and password.

Step 1: Adding username and password for admin database by using below steps.

# mongo
> show dbs
Output shows the database names like below.
admin 0.000GB
config 0.000GB
local 0.000GB

You must first connect to the database by using below command.
> use admin
You can create username and password for this database by using below command.
> db.createUser( {user: "username",pwd: "strong password",roles: [ { role: "userAdminAnyDatabase", db:"admin" },{ role: "dbAdminAnyDatabase", db: "admin" },{ role:"readWriteAnyDatabase", db: "admin" } ]})
Exit the Database.
> exit

Step 2: Open the configuration file by using the below command. Scroll down to find the commented-out security section and uncomment this line by removing # simbol.

# vim /etc/mongod.conf

Step 3: Add the authorization parameter and set it to "enabled" like below. Save and exit the file.

security:
authorization: "enabled"

Step 4: Restart the Mongodb service and check the status by using below commands.
# systemctl restart mongod
# systemctl status mongod

Step 5: You have to make sure the authentication is working for this admin database so you need login to mongodb via terminal by using below command
# mongo -u username -p --authenticationDatabase admin
Once you enter the above command will ask password for the username.
Password:

Thank you!

Leave a Reply