Mongodb enable authentication (Enable Access Control)

Mongodb enable authentication

Hi Folks,

In the context of databases, authentication acquires one more dimension because it may happen at different levels. It may be performed by the database itself, or the setup may be changed to allow either the operating system, or some other external method, to authenticate users.

Usually most of the databases like MySQL, MS SQL, Postgres, etc. comes with basic level of authentication. But in case of MongoDB the same cannot be said. MongoDB comes without any default authentication mechanisms. This provides restriction free access to all the users who can access any database or any data within it. This in trun raises security concerns.

There is a way provided to set up username and passwod for accessing the MongoDB in the official documentation. But the details provided are not clear enough to re-produce the same.

In this blog, we are going to see an elaborate step wise description on how to enable authentication for the accessing the MongoDB. The details specified below are for MongoDB 3.X version.

$ mongod --port 27017 --dbpath /data/db1
$ mongo --port 27017

Add a user with the root role. For example, the following creates the user superAdmin on the admin database:

$ use admin
$ db.createUser(
user: "superAdmin",
pwd: "admin123",
roles: [ { role: "root", db: "admin" } ]

Add the security.authorization setting to the config file

ubuntu: $ sudo vi /etc/mongod.conf
osx with brew version: $ sudo vi /usr/local/etc/mongod.conf

It may look like this

destination: file
path: /usr/local/var/log/mongodb/mongo.log
logAppend: true
dbPath: /usr/local/var/mongodb
authorization: enabled

Restart mongodb

ubuntu: $ sudo service mongod restart
osx with brew version: $ brew services restart mongodb
$ mongo --port 27017 -u "superAdmin" -p "admin123" --authenticationDatabase "admin"
$ mongo --port 27017 -u "superAdmin" -p "admin123" --authenticationDatabase "admin"
$ use myAppDb
$ db.createUser(
user: "myAppDbUser",
pwd: "myApp123",
roles: [ "readWrite"]
$ mongo --port 27017 -u "myAppDbUser" -p "myApp123" --authenticationDatabase "myAppDb"

More user roles here Build in Roles

Source Mongodb Enable Client Access Control



Lead Machine Learning Engineer @OptiSol

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store