Enabling access control on a MongoDB deployment enforces authentication, requiring users to identify themselves. When accessing a MongoDB deployment that has access control enabled, users can only perform actions as determined by their roles.
For authentication, MongoDB supports various Authentication Mechanisms.
The following tutorial enables access control on a standalone mongod
instance and uses the default authentication mechanism.
With access control enabled, ensure you have a user with userAdmin or userAdminAnyDatabase role in the admin database. This user can administrate user and roles such as: create users, grant or revoke roles from users, and create or modify customs roles.
You can create users either before or after enabling access control. If you enable access control before creating any user, MongoDB provides a localhost exception which allows you to create a user administrator in the admin database. Once created, you must authenticate as the user administrator to create additional users as needed.
The following procedure first adds a user administrator to a MongoDB instance running without access control and then enables access control.
mongod --port 27017 --dbpath /data/db1
You don't necessarily need the —port
or --dbpath
options if you're running locally
mongo --port 27017
In the admin database, add a user with the userAdminAnyDatabase role. Include additional roles as needed for this user. For example, the following creates the user myUserAdmin in the admin database with the userAdminAnyDatabase role and the readWriteAnyDatabase role.
use admin
db.createUser(
{
user: "harperAdmin",
pwd: "PdHgVezzd9wQ",
roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
}
)