How to Enhance the Security of MongoDB?

30-01-2024 03:02:02

The default configuration of MongoDB is not secure. Merely installing MongoDB without additional configurations can expose you to significant security risks. Hackers might gain the ability to read, write, modify, or even delete data within your database. Enhancing the security of MongoDB is not difficult and can be achieved by following these steps.

Firstly, initiate the Mongo client. On a Linux cloud server, this can be done by executing the mongo command. Enter the following text, replacing the uppercase English letters with actual information.

db.createUser({
  user: "USERNAME", 
  pwd: "PASSWORD", 
  roles: [
    {
      role: "readWrite",
      db: "YOUR_DATABASE"
    }
  ]
});

After completion, exit the Mongo client and edit the MongoDB configuration file. Depending on the version of the operating system, the name of this file could be either /etc/mongodb.conf or /etc/mongod.conf. Modify the line containing security to the following content:

security:
  authorization: enabled

On the other hand, if the bound port's IP address is a public IP, it should be changed to localhost (127.0.0.1) or a private IP address. Exposing your database to the public internet is also a very poor practice.

# network interfaces
net:
  port: 27017
  bindIp: 127.0.0.1

Finally, restart MongoDB to apply these settings. Depending on your operating system version, the command to restart MongoDB might be one of the following two.

systemctl restart mongod
systemctl restart mongodb