Enable Authentication – Create Admin/Root User in MongoDB

Database

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:

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:

Create mongo-admin user:

Create mongo-root user:

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:

Restart mongod to apply modifications:

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:

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

Share: