How to enable the mongo Database authentication method

Date: 09/01/2020

Introduction

Having an authentication for a database can not be a choice. Some may find it not necessary when it confined only use the database locally. It’s incredibly important to set up authentication if you are only using it locally. In this, we will discuss setting up root user and DB specific users for Mongo DB.

Create Admin/Root user

By default, mongo will have mongo-root as root user under admin database. To create new root user do

db.createUser(
{
    user: "root",
    pwd: "password",
    roles: [ "root" ]
})

To Change existing root user password

use admin # to list admin users
db.changeUserPassword('mongo-root' , 'XXXXXXX');

Sometime you may want to change the password of the root when you logged out from Mongo DB. In that case edit /etc/mongo.conf and set
security:
# auth = true

notauth = true

or
authentication = 'enabled'

Restart the DB
systemctl restart mongod

Create DB Specific User

To create a DB user

db.createUser(
              { user: 'dbuser', 
                pwd: 'xxxxxx', 
                roles: [ 
                        { role: 'userAdmin', db: 'dbname'}, 
                        { role: 'readWrite', db: 'dbname'},  
                        {role: 'dbAdmin', db: 'dbname'} 
                       ]
              });

you could find many different kinds of roles for Mongo DB. But I confined to create with mention essential roles

To access through CLI,

monog -u dbuser -p 'xxxxxx' 127.0.0.1/dnname

Great job. you know the creating users’ process in Mongo DB. If you find it useful, share it within your circle.

Leave a Reply