MongoDB: Managing users and roles (privileges)

Updated: February 1, 2024 By: Guest Contributor Post a comment

Introduction

MongoDB is a powerful, open-source NoSQL database that supports flexible data structures, easy scalability, and efficient performance. Understanding how to manage users and roles is critical for maintaining database security. In this tutorial, we’ll explore how to create users, define roles, and grant privileges in MongoDB. Irrespective of whether you’re running a local instance or deploying on a large-scale, these steps will help you lock down access to sensitive data and functions within your database.

Prerequisites

  • MongoDB installed and running
  • Basic knowledge of MongoDB operation
  • Access to the mongo shell or a MongoDB UI management tool

Understanding Authentication and Authorization

In MongoDB, authentication is the process of verifying the identity of a user, while authorization involves granting that user permission to perform certain actions. Roles are key to the authorization process, defining what a user can and cannot do.

Creating Users

To get started, you’ll need to create a user with appropriate permissions. Let’s create a basic user with read-only access:

use admin
db.createUser({
  user: 'myReadOnlyUser',
  pwd: 'password',
  roles: [
    { role: 'read', db: 'myDatabase' }
  ]
})

After applying this code in the mongo shell, you will have a new user named myReadOnlyUser that can only read documents within myDatabase.

Granting Privileges

Once a user is created, you can grant additional privileges as necessary. You can manage users’ roles using the grantRolesToUser function:

use admin
db.grantRolesToUser('myReadOnlyUser', [
  { role: 'readWrite', db: 'myDatabase' }
])

This command grants the user myReadOnlyUser both read and write privileges to myDatabase.

Defining Custom Roles

For complex use cases, MongoDB allows you to define custom roles. Let’s create a new role that combines read access to myDatabase and backup privileges:

use admin
db.createRole({
  role: 'readAndBackup',
  privileges: [
    { resource: { db: 'myDatabase', collection: '' }, actions: [ 'find', 'backup' ] }
  ],
  roles: []
})

Note that the collection field is set to an empty string, which means that this role has the associated actions applied to all collections within the specified database.

Assigning Custom Roles

With your new role created, you can assign it to a user. For example:

use admin
db.grantRolesToUser('myReadOnlyUser', ['readAndBackup'])

This gives our existing user the ability to back up the database in addition to the read permissions already granted.

Revoking Privileges

Sometimes you need to revoke privileges for security reasons. This can be done using the revokeRolesFromUser command:

use admin
db.revokeRolesFromUser('myReadOnlyUser', ['readWrite'])

Now, the myReadOnlyUser will no longer have write access to the database.

Advanced Role Configuration

For enterprises using MongoDB, there might be a need for finely grained access control. Let’s define a role that allows a user to insert data but not to read or modify existing data:

use admin
db.createRole({
  role: 'writeOnly',
  privileges: [
    { resource: { db: 'myDatabase', collection: '' }, actions: [ 'insert' ] }
  ],
  roles: []
})

This writeOnly role could be essential in scenarios where data is submitted by one team (or system) and processed by another, providing strict data submission control without read access.

Viewing User and Role Information

It’s essential to periodically review user and their roles. To list all users within the database, you can use:

use myDatabase
db.getUsers()

and to view all roles:

use myDatabase
db.getRoles()

It will display detailed information such as user names, user roles, and the roles’ defined privileges.

User and Role Management Best Practices

Here are some tips and best practices for managing your MongoDB users and roles:

  • Follow the principle of least privilege: only grant the permissions necessary for a user to perform their job.
  • Regularly update your users’ passwords and roles to reflect their current job requirements and to lock down any potential vectors for data breach.
  • Keep an audit log of who did what within your MongoDB instance, either by using MongoDB’s native auditing features or through external tools.

Conclusion

Mastering user and role management is essential for maintaining a secure and efficient MongoDB environment. Whether you are working with built-in roles or creating advanced customized roles, always ensure you review and apply best practices. By understanding user privileges and their impact, you’ll be able to better safeguard your data against unauthorized access and ensure optimal database performance.