Database

Enable Authentication – Create Admin/Root User in MongoDB

By default, authentication is disabled in MongoDB, but this is not so critical as, out of the box, MongoDB is listening on localhost only.

If you are going to allow remote connections to MongoDB, then it is definitely needed to enable authentication.

In the following article i will show how to enable authentication in MongoDB and how to create admin and root users.

Read more: Allow remote access to MongoDB 

Create Admin/Root User in MongoDB

Connect to MongoDB using mongo shell:

 $ mongo

Authentication Database: In MongoDB, user can have privileges across different databases. When adding a user, you create the user in a specific database. This database is the authentication database for this user.

Switch to admin database:

 > use admin

Create mongo-admin user:

 > db.createUser( { user: "<strong>mongo-admin</strong>", pwd: "<strong>passw0rd</strong>", roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] } )

Create mongo-root user:

 > db.createUser( { user: "mongo-root", pwd: "passw0rd", roles: [ { role: "root", db: "admin" } ] } )

Admin vs Root: The role userAdminAnyDatabase in MongoDB gives ability to create users and assign roles to them, but by itself it doesn’t allow the user to do anything else. The superuser role in MongoDB is the root.

Enable Authentication in MongoDB

Open MongoDB configuration file /etc/mongod.conf and enable auth:

 security: authorization: "enabled"

Restart mongod to apply modifications:

$ sudo service mongod restart

As only authentication is enabled, you won’t be able to execute MongoDB commands without being authenticated:

“errmsg” : “command listDatabases requires authentication”,
“code” : 13,
“codeName” : “Unauthorized”

Switch to the authentication database (in our case, admin) and authenticate:

 > use admin > db.auth("mongo-admin", "passw0rd" ) - or - > db.auth("mongo-root", "passw0rd" )

Source: MongoDB: Auth – Enable Authentication – Create Admin/Root User

Share:
Leave a Comment
Share
Published by
itfromzero
Tags: MongoDB

Recent Posts

Configure IP Network with ‘nmtui’ Tool

An alternative for the nmcli is the nmtui, short for Network Manager Text User Interface,…

4 years ago

Install MariaDB on Debian 9 (Stretch)

MariaDB is an enhanced, drop-in replacement for MySQL. MariaDB can be a better choice for…

5 years ago

Install MariaDB on Ubuntu 18.04 LTS

MariaDB is an enhanced, drop-in replacement for MySQL. MariaDB can be a better choice for…

5 years ago

Sync Files Directories from Different Cloud Storage with Rclone

Rclone is a command line program written in Go language, used to sync files and…

5 years ago

Python Pip Basic Commands

What is Pip? pip is a tool for installing and managing Python packages. With pip…

5 years ago

Install LAMP (Apache, MySQL & PHP) on Fedora 28/27/26

LAMP Stack is known as Linux, Apache, MySQL, and PHP. This is the popular web…

5 years ago