MongoDB runs without any authentication or authorization by default, making it quick and easy to get going. However, once things move to production it’s often a requirement and good security practice to have at least some basic authorization to protect your data.

In this post, we’ll walk through the steps to create MongoDB system users: the admin user, MMS monitoring agent user, and MMS backup agent user. The last two are of course only necessary if you use these services.

Creating MongoDB system users

We begin by starting a clean MongoDB standalone instance in a terminal window:

Now we can create the following three MongoDB system users: admin, monitoring (for MMS Monitoring), and backup (for MMS Backup) with the following Javascript snippet:

This can be executed by copying and pasting it into the Mongo Shell. Alternatively, save it to a file called create-system-users.js and run it:

MongoDB versions before 2.6

MongoDB versions before 2.6 do not have the built-in roles root, clusterMonitor, and backup. So use the following snippet instead:

Similarly, this can be saved to a file (e.g. create-system-users-pre2.6.js) and executed:

Refer to the root role, monitoring agent, and backup agent documentation for details.

Enabling authentication

Now that we have created the system users, we can restart MongoDB with authentication enabled. Terminate the MongoDB instance by pressing Ctrl-C in the terminal window we started it in, and restart with the following command:

Now let’s see if our configured authentication and authorization works by connecting to the mongo shell without logging in and listing the databases:

Let’s try again with the proper login:

It now works as expected.

In the next post of this series, we’ll look at a more complex example of creating application users that have restricted access.