Securing MongoDB

Updated on January 8, 2020
Securing MongoDB header image

Introduction

MongoDB is not secure by default. If you are installing MongoDB and launching it without configuring it for authentication, you are going to have a bad time. People can read, write, destroy, or alter data on your server without ever needing to login or authenticate in anyway. Securing the database is not hard to do and can be done in a few steps.

Secure MongoDB

First, start up your Mongo client. On Linux it is the command mongo. Enter this block of text in, of course changing the placeholder parts to your own information.

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

After you’re done, quit the mongo client and edit your MongoDB configuration file. Depending on your OS and distro, you will find it in one of these places.

/etc/mongodb.conf
/etc/mongod.conf

Change the following line, #security: to the following.

security:
  authorization: enabled

You should consider changing the bind port to localhost (127.0.0.1) or bind it to a private IP that does not get exposed to the internet. Exposing your database to the internet is just a bad idea in general. This is what you should change.

# network interfaces
net:
  port: 27017
  bindIp: 634.234.102.6

Mind your spaces! Always in twos, never tabs. Afterwards restart your MongoDB database. On Linux it will be one of the following commands based on your distro of choice.

systemctl restart mongod
systemctl restart mongodb