OPTIONS
翻译或纠错本页面

Assign a User a Role

在 2.6 版更改.

概述

A role provides a user privileges to perform a set of actions on a resource. A user can have multiple roles.

In MongoDB systems with authorization enforced, you must grant a user a role for the user to access a database resource. To assign a role, first determine the privileges the user needs and then determine the role that grants those privileges.

For an overview of roles and privileges, see 授权. For descriptions of the access each built-in role provides, see the section on built-in roles.

Prerequisites

You must have the grantRole action on a database to grant a role on that database.

To view a role’s information, you must be explicitly granted the role or must have the viewRole action on the role’s database.

Procedure

1

Connect with the privilege to grant roles.

Connect to the mongod or mongos either through the localhost exception or as a user with the privileges required in the Prerequisites section.

The following example operation connects to the MongoDB instance as a user named roleManager:

mongo --port 27017 -u roleManager -p 12345678 --authenticationDatabase admin
2

Verify your privileges.

Use the usersInfo command with the showPrivileges option.

The following example operation checks privileges for a user connected as manager:

db.runCommand(
  {
    usersInfo:"manager",
    showPrivileges:true
  }
)

The resulting users document displays the privileges granted to manager.

3

Identify the user’s roles and privileges.

To display the roles and privileges of the user to be modified, use the db.getUser() and db.getRole() methods, as described in Verify User Privileges.

To display the privileges granted by siteRole01 on the current database, issue:

db.getRole( "siteRole01", { showPrivileges: true } )
4

Identify the privileges to grant or revoke.

Determine which role contains the privileges and only those privileges. If such a role does not exist, then to grant the privileges will require creating a new role with the specific set of privileges. To revoke a subset of privileges provided by an existing role: revoke the original role, create a new role that contains the privileges to keep, and then grant that role to the user.

5

Grant a role to a user.

Grant the user the role using the db.grantRolesToUser() method.

For example:

use admin
db.grantRolesToUser(
  "accountAdmin01",
  [
    {
      role: "readWrite", db: "products"
    },
    {
      role: "readAnyDatabase", db:"admin"
    }
  ]
)