Navigation
This version of the documentation is archived and no longer supported.

Enable Client Access Control

Overview

Enabling access control on a MongoDB instance restricts access to the instance by requiring that users identify themselves when connecting. In this procedure, you enable access control and then create the instance’s first user, which must be a user administrator. The user administrator grants further access to the instance by creating additional users.

Considerations

If you create the user administrator before enabling access control, MongoDB disables the localhost exception. In that case, you must use the “Enable Authentication after Creating the User Administrator” procedure to enable access control.

This procedure uses the localhost exception to allow you to create the first user after enabling authentication. See Localhost Exception and Authentication for more information.

Procedure

1

Start the MongoDB instance with authentication enabled.

Start the mongod or mongos instance with the authorization or keyFile setting. Use authorization on a standalone instance. Use keyFile on an instance in a replica set or sharded cluster.

For example, to start a mongod with authentication enabled and a key file stored in /private/var, first set the following option in the mongod’s configuration file:

security:
  keyFile: /private/var/key.pem

Then start the mongod and specify the config file. For example:

mongod --config /etc/mongodb/mongodb.conf

After you enable authentication, only the user administrator can connect to the MongoDB instance. The user administrator must log in and grant further access to the instance by creating additional users.

2

Connect to the MongoDB instance via the localhost exception.

Connect to the MongoDB instance from a client running on the same system. This access is made possible by the localhost exception.

3

Create the system user administrator.

Add the user with the userAdminAnyDatabase role, and only that role.

The following example creates the user siteUserAdmin user on the admin database:

use admin
db.createUser(
  {
    user: "siteUserAdmin",
    pwd: "password",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)

After you create the user administrator, the localhost exception is no longer available.

The mongo shell executes a number of commands at start up. As a result, when you log in as the user administrator, you may see authentication errors from one or more commands. You may ignore these errors, which are expected, because the userAdminAnyDatabase role does not have permissions to run some of the start up commands.

4

Create additional users.

Login in with the user administrator’s credentials and create additional users. See Add a User to a Database.

Next Steps

If you need to disable access control for any reason, restart the process without the authorization or keyFile setting.