Enable Authentication In MongoDB

MongoDB is one of the most used NoSQL database systems with many features. Security is one of the essential things in any system and for a database, it is most important. In this post, I will explain to you how to configure Authentication security in the MongoDB database.

Setup Authentication in MongoDB

By default, MongoDB installation or docker image has no authentication enabled. You can connect directly without using any DB credentials. To enable security we need to set up users and then change configurations.

There are many inbuilt roles in MongoDB and You can use appropriate roles according to your need. Users can be created in the system database for system administrative roles and Database specific user’s can be created in that database.

You can use the command line client and Robo T3 client to create users. In this tutorial, I am going to create use in the admin database.

use admin
    user: "myadmin",
    pwd: "abc123",
    roles: [ { role: "dbAdminAnyDatabase", db: "admin" } ]

above script will create myadmin user in admin database with DB admin any database role. This means this user can do all tasks in all databases.

You can also create users using Robo T3 or other GUI tools of MongoDB.

In Robo T3 right click on users in the selected DB and select create user command. This will open create user dialog when you can enter your username, password, source DB, and select roles.

Now you need to change the configuration of MongoDB, it depends upon installation, Version, and the underlying OS.

Changing Mongo Security in On Linux

First, un-comment the line that starts with #auth=true in your mongod configuration file (default path /etc/mongod.conf). This will enable authentication for MongoDB.

in the newer version mongod.conf is yaml file and you can change like below

    authorization: "disabled"

Then, restart MongoDB

sudo service mongod restart

Changing Mongo Security in Docker

To run docker with authentication enabled using mongod -auth parameter while running docker.

docker run -d -p 27017:27017 --name test-mongo mongo:latest mongod --auth

Now you need to connect MongoDB using your user and password.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.