Lesson 3: Establishing Authorization for a Self-Managed MongoDB Deployment / Learn

Code Summary: Establishing Authorization for a Self-Managed MongoDB Deployment

Review the following code, which demonstrates how to assign a built-in role to a database user, authenticate to a database as a specific user, and remove a built-in role from a database user.

Assign a Built-In Role to a Database User

To assign a built-in role to a database user, first connect to the instance to authenticate as the user administrator:

mongosh --username globalUserAdmin

When prompted, enter the globalUserAdmin password. Then switch to the admin database:

use admin

Use the db.createUser method to create the analystUser:

db.createUser(
  {
    user: "analystUser",
    pwd: passwordPrompt(),        
    roles: [
      { role: "read", db: "sample_analytics" },
    ]
  }

When prompted, enter a password for analystUser. Then quit the shell session:

quit()

Authenticate to the Database by Using the analystUser

To authenticate as analystUser, reconnect to the mongod:

mongosh "mongodb://analystUser@localhost:27017/sample_analytics?authSource=admin"

When prompted, enter the password.

Run show collections to get a list of all collections in the database:

show collections

Query for a document in the accounts collection:

db.accounts.findOne()

Quit the current shell session:

quit()

Remove a Built-In Role from a Database User

The following code demonstrates how to remove a built-in role from a database user. In this example, we’re removing a role from financeUser.

First, authenticate as the user administrator by connecting to the MongoDB instance using mongosh:

mongosh --username globalUserAdmin

When prompted, enter the password.

Use the admin database, because that’s where financeUser was created.

use admin

Confirm financeUser’s current roles by using the db.getUser method to retrieve user information about financeUser:

db.getUser("financeUser")

Remove financeUser’s read role on sample_training by using the db.revokeRolesFromUser method:

db.revokeRolesFromUser(
    "financeUser",
    [
      { role: "read", db: "sample_training" }
    ]
)

Finally, review the updated information about financeUser’s roles by running db.getUser again:

db.getUser("financeUser")