DEV Community

Cover image for [Day 6] Securing MongoDB
Wojciech Wernicki
Wojciech Wernicki

Posted on

[Day 6] Securing MongoDB

Hello guys!

After installing MongoDB on my machine, it's time to secure access to databases.

Change default port

In file /etc/mongod.conf in section net I changed value of port from default 27017 to 5652:

...
net:
  port: 5652
...
Enter fullscreen mode Exit fullscreen mode

and restarted service with the command sudo systemctl restart mongod.

Create a user with administrative rights

After I changed default port when I want to access MongoDB in console, I have to provide new port:

mongo --port 5652
Enter fullscreen mode Exit fullscreen mode

After successful access, it's time to create a new user with administrative rights:

use admin

db.createUser(
    {
        user: "JohnDoe",
        password: passwordPrompt(),
        roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
    }
)
Enter fullscreen mode Exit fullscreen mode

After confirmation, I need to pass a new password for the user, all thanks to passwordPrompt. To be sure I can access MongoDB via new user, I exit and log in again with the expended command:

mongo --port 5652 -u JohnDoe -p --authenticationDatabase admin
Enter fullscreen mode Exit fullscreen mode

and type in the password.

Enforcing login credentials

Once again I'm heading into /etc/mongod.conf file, where I should change security section:

...
security:
  authorization: "enabled"
...
Enter fullscreen mode Exit fullscreen mode

and restarted once again service with the command sudo systemctl restart mongod.

From now accessing MongoDB with authorization won't trigger any alert or access denial, but after typing in show dbs nothing will be returned. If I want to see databases, I have to authorize myself the same way after I check if my new account does work.


That was a pretty long process to secure databases. At this moment, I don't want to allow any external access to MongoDB, so it is hidden behind the firewall.

References


Cover image: Photo by Dayne Topkin on Unsplash

Top comments (0)