How to manage users and authentication in MongoDB/MongoDB Role-Based Access Control

How to manage users and authentication in MongoDB

Managing users and authentication are some of the most important administration tasks of managing MongoDB servers. You must ensure that the server is configured to be able to properly identify your users and applications and deny connections or operations that are unable to authenticate correctly.

To manage these requirements, you must be able to decide which the users your server requires and create those accounts. As part of this process, you can set the authentication details to allow external access using the new identity.

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.

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.


Commands and methods we will use:-

To create, modify, and delete users within MongoDB and configure authentication, the core methods you need are:

  • db.createUser: create a new MongoDB user account.
Now we are going to login mongodb and run given below command for create user;-

db.createUser( {

user: "test_user",

pwd: "Test@123@123",

roles: [ { role: "root", db: "admin" } ]

} );


  • db.getUsers(): How to check existing user in mongodb:
To return multiple users, you can use the db.getUsers() and show users method on to show all of the users within the current database. First, switch to the database you're interested in querying:

use admin;

Next, use the db.getUsers() and show users method to return all of the users associated with the current database:


  • db.updateUser: update the details of a user account
To changes a user name ,you can use the 
db.system.users.update({"user":"oldname"}, {$set:{"user":"newname"}}) method you must switch to the user's authentication database before executing the command.

now we are going to create user username test_user and after that we will rename user pmsl_test.



  • db.changeUserPassword: change the password used by a user account

To change a user's password, you can use the db.changeUserPassword() method. Again, you must switch to the user's authentication database before executing the command.

The db.changeUserPassword() method takes two arguments: the username of the account you wish to change and the new password for the account.

For instance, to change the password for the user tom authenticated with the admin database to secretpassword, you could type:

use admin
db.changeUserPassword("tom", "secretpassword");



Just as with the db.createUser() method, you can use the passwordPrompt() method for the second argument instead of providing a password inline. MongoDB will prompt you to enter a password when the command is executed:

use admin
db.changeUserPassword("tom", passwordPrompt());



  • db.dropUser: delete a MongoDB user account
To remove MongoDB user accounts, you can use the db.dropUser() method. Be sure to connect to the user's authentication database before removing them.


  • db.runCommand('usersInfo'): show information about one or more MongoDB user accounts

The same operation using the createUser database command would look like this:

db.runCommand({
    createUser: "tom",
    pwd: "hellothere",
    roles: []
})



MongoDB Role-Based Access Control:-
MongoDB access control enables database administrators to secure MongoDB instances by enforcing user authentication. MongoDB supports multiple authentication methods and grants access through role-based authorization.

Roles are the foundation blocks in MongoDB, providing user isolation for a great degree of security and manageability.


How MongoDB RBAC works:-

A user can be assigned one or more roles, and the scope of user access to the database system is determined by those assigned roles. Users have no access to the system outside the designated roles.

Importantly, MongoDB access control is not enabled by default; you have to enable it through the security.authorization setting.

When that setting is enabled, users need to authorize themselves before interacting with the database. User privileges can include a specific resource (database, collection, cluster) and actions permitted on that resource.

A role grants permission to perform particular actions on a specific resource. A single user account can consist of multiple roles. Roles can be assigned:

  • At the time of user creation
  • When updating the roles of existing users
There are two types of Roles in MongoDB:

  • Built-In Roles. MongoDB provides built-in roles to offer a set of privileges that are commonly needed in a database system.
  • User-Defined Roles. If built-in roles do not provide all the expected privileges, database administrators can define custom roles using the createRole method. Those roles are called User-Defined roles.


Database user roles:-
Database user roles are normal user roles that are useful in regular database interactions.

  • Read:Read all non-system collections and the system.js collection
  • Read/Write:Both Read and Write functionality on non-system collections and the system.js collection
Database administration roles:-
These are roles that are used to carry out administrative operations on databases.
  • dbAdmin: Perform administrative tasks such as indexing and gathering statistics, but cannot manage users or roles.
  • userAdmin: Provides the ability to create and modify roles and users of a specific database.
  • dbOwner: This is the owner of the database who can perform any action. It is equal to combining all the roles mentioned above: readWrite, dbAdmin, and userAdmin roles.
Cluster admin roles:-
These roles enable users to interact and administrate MongoDB clusters.

  • clusterManager: Enables management and monitoring functionality on the cluster. Provides access to config and local databases used in sharding and replication
  • clusterMonitor: Provide read-only access to MongoDB monitoring tools such as Cloud Manager or Ops Manager monitoring agent
  • hostManager: Provides the ability to monitor and manage individual servers
  • clusterAdmin: This role includes the highest number of cluster administrative privileges allowing a user to do virtually anything. This functionality is equal to the combination of clusterManager, clusterMonitor, hostManager roles, and dropDatabase action.
Backup & restoration roles:-
These are the roles that are required for backup and restoring data in a MongoDB instance. They can only be assigned with the admin database.


  • backup: Provides the necessary privileges to backup data. This role is required for MongoDB Cloud Manager and Ops Manager, backup agents, and the monogdump utility.
  • restore: Provides the privileges to carry out restoration functions
All database roles:-
These are database roles that provide privileges to interact with all databases, excluding local and config databases.

  • readAnyDatabase: Read any database
  • readWriteAnyDatabase: Provides read and write privileges to all databases
  • userAdminAnyDatabase: Create and Modify users and roles across all databases
  • dbAdminAnyDatabase: Perform database administrative functions on all databases
Superuser roles:-
MongoDB can provide either direct or indirect system-wide superuser access. The following roles grant superuser privileges scoped to a specified database or databases.

  • dbOwner
  • userAdmin
  • userAdminAnyDatabase
The true superuser role is the root role, which provides systemwide privileges for all functions and resources.

User-Defined Roles:-

In situations where built-in roles are unable to provide the necessary privileges covering the scope of the access requirements or to restrict the scope and actions of a user, you can define custom User-Defined roles.

MongoDB Role Management provides the necessary methods to create and manage user-defined roles. The most commonly used methods for user-defined role creation are shown in the following table. (A complete list of methods can be found here.)


  • db.createRole():- Create a role and its privileges
  • db.updateRole():- Update the user-defined role
  • db.dropRole():- Delete a user-defined role
  • db.grantPrivilegesToRole():- Assigns new privileges to a role
  • db.revokePrivilegesFromRole():- Removes privileges from a role
MongoDB role management:-
In this section, Let’s discuss how to create and modify roles within a MongoDB instance.

Roles are defined using the following syntax:

Copy
roles: [
{
role: "<Role>", db: "<Database>"
}
]

Assigning user roles at user creation:-
First, create a user with read and write access to a specific database (supermarket) using the createUser method with roles parameter.


db.createUser(
{
user: "piter",
pwd: "piter@123",
roles: [
{
role: "readWrite",
db: "crudoperation"
}
]
}
)

Output:-

Then, create an administrative user to the supermarket database with roles granting read access to all other databases and the backup and restore functions.

db.createUser(
{
user: "pmsl",
pwd: "pmsl@123",
roles: [
{
role: "dbOwner", db: "crudoperation"
},
{
role: "readAnyDatabase", db: "admin"
},
{
role: "backup", db: "admin"
},
{
role: "restore", db: "admin"
}
]
}
)

Output:-

Retrieving role information:-
Using the getRole method, users can obtain information about a specific role. The below code shows how to get the details of the readWriteAnyDatabase role from the admin database.

db.getRole("readWriteAnyDatabase");


To obtain the privileges associated with that role, use the showPrivileges option by setting its value as ‘true’. This can also be used in the getUser method.


Identifying assigned user roles:
The getUser method enables you to identify the roles assigned to a specific user by using the following syntax:

db.getUser("<Username>")


Granting & revoking user roles:-
Using the grantRolesToUser and revokeRolesFromUser methods, you can modify the roles assigned to existing users. These methods use the following syntax:

db.<grantRolesToUser | revokeRolesFromUser> (
"<Username>",
[
{ role: "<Role>", db: "<Database>" }
]
)

The below example shows how to grant user roles. You will add a new role to the user “harry” providing the necessary privileges to act as the database admin (dbAdmin) to gather statistics from the “vehicles” table.

db.grantRolesToUser(
"harry",
[
{ role: "dbAdmin", db: "vehicles" }
]
)

output:-

Now you have added a new role to the user, “harry”. So, let’s remove that newly granted role using the revokeRolesFromUser method.

db.revokeRolesFromUser(
"harry",
[
{ role: "dbAdmin", db: "vehicles" }
]
)

output:-

Creating user-defined roles:-
Using the createRole method, you can create a new role according to your needs. The basic structure of the createRole method is shown below.

Note: Using the roles parameter within the createRole method allows you to inherit the privileges of other roles within the user-defined role. If no other privileges are required, you need to define an empty roles parameter when creating a user-defined role.

db.createRole(
{
role: "<RoleName>",
privileges: [
{
resource: { db: "<Database>", collection: "<Collection>"},
actions: [ "<Actions>" ]
}
],
roles: [
{ role: "<Role>", db: "<Database>" }
]
}
)

To associate a user-defined role to all databases or collections, you can specify the resources with empty double quotes, as shown below.

resource: { db: "", collection: ""}

In the next code block, you will create a role that limits a user’s access to a specific database collection (inventory collection of supermarket database). It limits the user actions to find and update commands without inheriting any other privileges.


We can identify the user-defined roles using the isBuiltin parameter. The inventoryeditor role has false for the that parameter, indicating it as a non-built-in role.

Now you know how to create a standalone user-defined role. Next, you will create a user-defined role that inherits some privileges from another built-in role.

In the below code block, you will create an inventorymanager role with all the CURD privileges and inherit the privileges from the userAdmin role.

db.createRole(
{
role: "inventorymanager",
privileges: [
{
resource: { db: "supermarket", collection: "inventory"},
actions: [ "find", "update", "insert", "remove" ]
}
],
roles: [
{ role: "userAdmin", db: "supermarket" }
]
}
)

output:-


Assigning user-defined roles to users:-

You can assign user-defined roles to a new user or update the roles of an existing user in the same way you do it with a built-in role. Let’s create a new user with the inventorymanager role assigned and update an existing user with the inventoryeditor role in the following examples.

Creating a new user:
db.createUser(
{
user: "DBA",
pwd: "Dba@123",
roles: [
{
role: "inventorymanager",
db: "admin"
}
]
}
)


Granting new roles:

db.grantRolesToUser(
"DBA",
[
{ role: "inventoryeditor", db: "admin" }
]
)

OutPut:-



Updating & deleting user-defined roles:-

You can update the user-defined roles using the updateRole method and delete the roles using the dropRole method.

Let’s update the inventoryeditor role with an additional privilege to create documents within the specified collection, in the below example.

db.updateRole(
"DBA",
{
privileges: [
{
resource: { db: "supermarket", collection: "inventory"},
actions: [ "find", "update", "insert" ]
}
],
roles: [ ]
}
)

The dropRole method has a single functionality to remove a user-defined role. You can remove the inventoryeditor role from the database, as shown below.

db.dropRole("inventoryeditor")












Comments

Popular posts from this blog

MySQL Point in Time Recovery: How To Configure And How Does it Work?

MySQL Replication Switchover: Step-by-Step Guide

Mysql Commercial Mysqlbackup:How to take Differential or Incremental Backup and resotre using mysqlbackup utility in mysql 8.0.37 enterprise edition