- Manage Users and Roles
- Overview
- Prerequisites
- Create a User-Defined Role
- Modify Access for an Existing User
- Modify the Password for an Existing User
- View a User’s Roles
- View a Role’s Privileges
Manage Users and Roles
Overview
This tutorial provides examples for user and role management under theMongoDB’s authorization model. Add Users describeshow to add a new user to MongoDB.
Prerequisites
Important
If you have enabled access control for your deployment, you mustauthenticate as a user with the required privileges specified in eachsection. A user administrator with theuserAdminAnyDatabase
role, or userAdmin
rolein the specific databases, provides the required privileges to performthe operations listed in this tutorial. SeeEnable Access Control for details on adding useradministrator as the first user.
Create a User-Defined Role
Roles grant users access to MongoDB resources. MongoDB provides anumber of built-in roles thatadministrators can use to control access to a MongoDB system. However,if these roles cannot describe the desired set of privileges, you cancreate new roles in a particular database.
Except for roles created in the admin
database, a role can onlyinclude privileges that apply to its database and can only inherit fromother roles in its database.
A role created in the admin
database can include privileges thatapply to the admin
database, other databases or to thecluster resource, and can inherit from rolesin other databases as well as the admin
database.
To create a new role, use the db.createRole()
method,specifying the privileges in the privileges
array and the inheritedroles in the roles
array.
MongoDB uses the combination of the database name and the role name touniquely define a role. Each role is scoped to the database in whichyou create the role, but MongoDB stores all role information in theadmin.system.roles
collection in the admin
database.
Prerequisites
To create a role in a database, you must have:
- the
createRole
action onthat database resource. - the
grantRole
action onthat database to specify privileges for the new role as well as tospecify roles to inherit from.
Built-in roles userAdmin
anduserAdminAnyDatabase
provide createRole
andgrantRole
actions on their respective resources.
To create a role with authenticationRestrictions
specified, youmust have the setAuthenticationRestriction
action on thedatabase resource which the role iscreated.
Create a Role to Manage Current Operations
The following example creates a role named manageOpRole
whichprovides only the privileges to run both db.currentOp()
anddb.killOp()
. [1]
Note
Changed in version 3.2.9: On mongod
instances, users do not need anyspecific privileges to view or kill their own operations. Seedb.currentOp()
and db.killOp()
for details.
Connect to MongoDB with the appropriate privileges.
Connect to mongod
or mongos
with the privilegesspecified in the Prerequisites section.
The following procedure uses the myUserAdmin
created inEnable Access Control.
- mongo --port 27017 -u myUserAdmin -p 'abc123' --authenticationDatabase 'admin'
The myUserAdmin
has privileges to create roles in the admin
as well as other databases.
Create a new role to manage current operations.
manageOpRole
has privileges that act on multiple databases as wellas the cluster resource. As such, you mustcreate the role in the admin
database.
- use admin
- db.createRole(
- {
- role: "manageOpRole",
- privileges: [
- { resource: { cluster: true }, actions: [ "killop", "inprog" ] },
- { resource: { db: "", collection: "" }, actions: [ "killCursors" ] }
- ],
- roles: []
- }
- )
The new role grants permissions to kill any operations.
Warning
Terminate running operations with extreme caution. Only usethe db.killOp()
method or killOp
command to terminate operations initiated by clientsand do not terminate internal database operations.
[1] | The built-in role clusterMonitor also provides theprivilege to run db.currentOp() along with otherprivileges, and the built-in role hostManager providesthe privilege to run db.killOp() along with otherprivileges. |
Create a Role to Run mongostat
The following example creates a role named mongostatRole
thatprovides only the privileges to run mongostat
.[2]
Connect to MongoDB with the appropriate privileges.
Connect to mongod
or mongos
with the privilegesspecified in the Prerequisites section.
The following procedure uses the myUserAdmin
created inEnable Access Control.
- mongo --port 27017 -u myUserAdmin -p 'abc123' --authenticationDatabase 'admin'
The myUserAdmin
has privileges to create roles in the admin
as well as other databases.
Create a new role to manage current operations.
mongostatRole
has privileges that act on the clusterresource. As such, you must create the role inthe admin
database.
- use admin
- db.createRole(
- {
- role: "mongostatRole",
- privileges: [
- { resource: { cluster: true }, actions: [ "serverStatus" ] }
- ],
- roles: []
- }
- )
[2] | The built-in roleclusterMonitor also provides the privilege to runmongostat along with otherprivileges. |
Create a Role to Drop system.views Collection across Databases
The following example creates a role nameddropSystemViewsAnyDatabase
that provides the privileges to drop thesystem.views
collection in any database.
Connect to MongoDB with the appropriate privileges.
Connect to mongod
or mongos
with the privilegesspecified in the Prerequisites section.
The following procedure uses the myUserAdmin
created inEnable Access Control.
- mongo --port 27017 -u myUserAdmin -p 'abc123' --authenticationDatabase 'admin'
The myUserAdmin
has privileges to create roles in the admin
as well as other databases.
Create a new role to drop the system.views collection in any database.
For the role, specify a privilege that consistsof:
- an
actions
array that contains thedropCollection
action, and - a resource document thatspecifies an empty string (
""
) for the database and the string"system.views"
for the collection. SeeSpecify Collections Across Databases as Resource for more information.
- use admin
- db.createRole(
- {
- role: "dropSystemViewsAnyDatabase",
- privileges: [
- {
- actions: [ "dropCollection" ],
- resource: { db: "", collection: "system.views" }
- }
- ],
- roles: []
- }
- )
Modify Access for an Existing User
Prerequisites
- You must have the
grantRole
action on a database to grant a role on that database. - You must have the
revokeRole
action on a database to revoke a role on that database. - To view a role’s information, you must be either explicitly granted therole or must have the
viewRole
action on the role’s database.
Procedure
Connect to MongoDB with the appropriate privileges.
Connect to mongod
or mongos
as a user withthe privileges specified in the prerequisite section.
The following procedure uses the myUserAdmin
created inEnable Access Control.
- mongo --port 27017 -u myUserAdmin -p 'abc123' --authenticationDatabase 'admin'
Identify the user’s roles and privileges.
To display the roles and privileges of the user to be modified, use thedb.getUser()
and db.getRole()
methods.
For example, to view roles for reportsUser
created inExamples, issue:
- use reporting
- db.getUser("reportsUser")
To display the privileges granted to the user by thereadWrite
role on the "accounts"
database, issue:
- use accounts
- db.getRole( "readWrite", { showPrivileges: true } )
Identify the privileges to grant or revoke.
If the user requires additional privileges, grant to the user therole, or roles, with the required set of privileges. If such a roledoes not exist, create a new rolewith the appropriate set of privileges.
To revoke a subset of privileges provided by an existing role: revokethe original role and grant a role that contains only the requiredprivileges. You may need to create a new role if a role does not exist.
Modify the user’s access.
Revoke a Role
Revoke a role with the db.revokeRolesFromUser()
method.The following example operation removes the readWrite
role on the accounts
database from the reportsUser
:
- use reporting
- db.revokeRolesFromUser(
- "reportsUser",
- [
- { role: "readWrite", db: "accounts" }
- ]
- )
Grant a Role
Grant a role using the db.grantRolesToUser()
method. For example, the following operation grants thereportsUser
user the read
role on theaccounts
database:
- use reporting
- db.grantRolesToUser(
- "reportsUser",
- [
- { role: "read", db: "accounts" }
- ]
- )
For sharded clusters, the changes to the user are instant on themongos
on which the command runs. However, for othermongos
instances in the cluster, the user cache may waitup to 10 minutes to refresh. SeeuserCacheInvalidationIntervalSecs
.
Modify the Password for an Existing User
Prerequisites
To modify the password of another user on a database, you must have thechangeAnyPassword
actionon that database.
Procedure
Connect to MongoDB with the appropriate privileges.
Connect to the mongod
or mongos
with the privilegesspecified in the Prerequisites section.
The following procedure uses the myUserAdmin
created inEnable Access Control.
- mongo --port 27017 -u myUserAdmin -p 'abc123' --authenticationDatabase 'admin'
Change the password.
Pass the user’s username and the new password to thedb.changeUserPassword()
method.
The following operation changes the reporting
user’s password toSOh3TbYhxuLiW8ypJPxmt1oOfL
:
- db.changeUserPassword("reporting", "SOh3TbYhxuLiW8ypJPxmt1oOfL")
See also
Change Your Password and Custom Data
View a User’s Roles
Prerequisites
To view another user’s information, you must have theviewUser
action on theother user’s database.
Users can view their own information.
Procedure
Connect to MongoDB with the appropriate privileges.
Connect to mongod
or mongos
as a user withthe privileges specified in the prerequisite section.
The following procedure uses the myUserAdmin
created inEnable Access Control.
- mongo --port 27017 -u myUserAdmin -p 'abc123' --authenticationDatabase 'admin'
Identify the user’s roles.
Use the usersInfo
command or db.getUser()
method todisplay user information.
For example, to view roles for reportsUser
created inExamples, issue:
- use reporting
- db.getUser("reportsUser")
In the returned document, the roles
field displays all roles for reportsUser
:
- ...
- "roles" : [
- { "role" : "readWrite", "db" : "accounts" },
- { "role" : "read", "db" : "reporting" },
- { "role" : "read", "db" : "products" },
- { "role" : "read", "db" : "sales" }
- ]
View a Role’s Privileges
Prerequisites
To view a role’s information, you must be either explicitly granted therole or must have the viewRole
action on the role’s database.
Procedure
Connect to MongoDB with the appropriate privileges.
Connect to mongod
or mongos
as a user withthe privileges specified in the prerequisite section.
The following procedure uses the myUserAdmin
created inEnable Access Control.
- mongo --port 27017 -u myUserAdmin -p 'abc123' --authenticationDatabase 'admin'
Identify the privileges granted by a role.
For a given role, use the db.getRole()
method, or therolesInfo
command, with the showPrivileges
option:
For example, to view the privileges granted by read
role onthe products
database, use the following operation, issue:
- use products
- db.getRole( "read", { showPrivileges: true } )
In the returned document, the privileges
andinheritedPrivileges
arrays. Theprivileges
lists the privileges directlyspecified by the role and excludes those privileges inheritedfrom other roles. The inheritedPrivileges
lists all privileges granted by this role, both directlyspecified and inherited. If the role does not inherit from otherroles, the two fields are the same.
- ...
- "privileges" : [
- {
- "resource": { "db" : "products", "collection" : "" },
- "actions": [ "collStats","dbHash","dbStats","find","killCursors","planCacheRead" ]
- },
- {
- "resource" : { "db" : "products", "collection" : "system.js" },
- "actions": [ "collStats","dbHash","dbStats","find","killCursors","planCacheRead" ]
- }
- ],
- "inheritedPrivileges" : [
- {
- "resource": { "db" : "products", "collection" : "" },
- "actions": [ "collStats","dbHash","dbStats","find","killCursors","planCacheRead" ]
- },
- {
- "resource" : { "db" : "products", "collection" : "system.js" },
- "actions": [ "collStats","dbHash","dbStats","find","killCursors","planCacheRead" ]
- }
- ]