Users and roles
Create users with MongoDB's built-in roles or with your own roles.
User and role commands are MongoDB's. Each command is authorized before it runs. If you lack the privilege, the
command answers Unauthorized (13).
Requirements
- A user with the
userAdminrole on the database oruserAdminAnyDatabase.
One user per application
db.getSiblingDB("admin").createUser({
user: "shop-api",
pwd: passwordPrompt(),
roles: [{ role: "readWrite", db: "shop" }],
});Built-in roles
read, readWrite, dbAdmin, dbOwner, userAdmin, clusterAdmin, clusterManager, clusterMonitor,
enableSharding, hostManager, backup, restore, readAnyDatabase, readWriteAnyDatabase,
userAdminAnyDatabase, dbAdminAnyDatabase and root, with the same privileges as in MongoDB.
Your own roles
db.getSiblingDB("admin").createRole({
role: "reports",
privileges: [{ resource: { db: "shop", collection: "orders" }, actions: ["find"] }],
roles: [],
});Revoke
When you revoke a role or drop a user, the command answers only once no node can authorize with the previous state. There is no window in which another node still lets the revoked user through.
Check
db.getSiblingDB("admin").runCommand({ usersInfo: "shop-api" });usersInfo answers with the user you just created and the roles it has, so you can confirm that shop-api got
the roles you granted it before your application starts using it to connect.
Common problems
- A command answers
Unauthorized(13) because the user lacks the privilege it needs. Look at its roles withusersInfoand grant the missing one withgrantRolesToUser.
See also
- REST API, with the API keys of a user.
- Authentication.