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

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.

Cool Tip: To allow remote access to MongoDB – change bindIp! Read More →

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: "mongo-admin",
    pwd: "passw0rd",
    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:

  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" )

Cool Tip: How to connect to remote MongoDB server from the command line using mongo shell! Read More →

Leave a Reply