0
0
MongoDBquery~15 mins

Creating users and roles in MongoDB - Mechanics & Internals

Choose your learning style9 modes available
Overview - Creating users and roles
What is it?
Creating users and roles in MongoDB means setting up who can access the database and what they are allowed to do. Users are like people with names and passwords, and roles are sets of permissions that say what actions those users can perform. This helps keep the database safe by controlling access. Without users and roles, anyone could see or change your data.
Why it matters
Without users and roles, your database would be open to anyone, risking data loss, theft, or damage. By creating users and assigning roles, you protect sensitive information and make sure only the right people can do certain tasks. This is essential for security, especially when many people or applications use the database.
Where it fits
Before learning this, you should understand basic MongoDB concepts like databases and collections. After this, you can learn about advanced security features like authentication mechanisms and auditing. This topic is part of managing and securing your MongoDB environment.
Mental Model
Core Idea
Users are identities with passwords, and roles are permission sets that define what those users can do in the database.
Think of it like...
Think of a library: users are library members with cards, and roles are the types of access they have, like borrowing books, reading in the library, or managing the collection.
┌─────────────┐      assigns      ┌─────────────┐
│   User A    │──────────────────▶│   Role X    │
└─────────────┘                   └─────────────┘
       │                               │
       │                               │
       ▼                               ▼
  Has password                  Has permissions
       │                               │
       ▼                               ▼
  Authenticates               Can read/write/delete
       │                               │
       ▼                               ▼
  Access granted             Controls database actions
Build-Up - 7 Steps
1
FoundationUnderstanding MongoDB Users
🤔
Concept: Users in MongoDB represent people or applications that connect to the database with a username and password.
In MongoDB, a user is created with a username and password. This user must authenticate to access the database. Users do not have permissions by themselves; they need roles to define what they can do.
Result
You create a user that can log in to MongoDB but cannot do anything until roles are assigned.
Knowing that users are just identities helps separate authentication (who you are) from authorization (what you can do).
2
FoundationWhat Are Roles in MongoDB?
🤔
Concept: Roles are collections of permissions that define what actions a user can perform on the database.
MongoDB has built-in roles like read, readWrite, dbAdmin, and userAdmin. Each role allows specific actions, such as reading data, writing data, or managing users. Roles can be assigned to users to grant these permissions.
Result
Assigning a role to a user gives that user the ability to perform the actions allowed by the role.
Separating roles from users allows flexible permission management and easier security control.
3
IntermediateCreating a User with Roles
🤔Before reading on: do you think you can create a user without assigning any role? Commit to your answer.
Concept: When creating a user, you must assign at least one role to give them permissions.
Use the command db.createUser({user: 'alice', pwd: 'password123', roles: [{role: 'readWrite', db: 'testdb'}]}) to create a user named 'alice' with read and write permissions on 'testdb'. Without roles, the user cannot perform any actions.
Result
User 'alice' can now read and write data in the 'testdb' database.
Understanding that roles are mandatory for permissions prevents confusion about why a user cannot do anything after creation.
4
IntermediateCustom Roles for Specific Permissions
🤔Before reading on: do you think built-in roles cover all permission needs? Commit to your answer.
Concept: You can create custom roles to grant very specific permissions not covered by built-in roles.
Use db.createRole({role: 'customRole', privileges: [{resource: {db: 'testdb', collection: ''}, actions: ['find', 'insert']}], roles: []}) to create a role that allows only reading and inserting documents in 'testdb'. Then assign this role to a user.
Result
Users with 'customRole' can only read and insert data, not update or delete.
Knowing how to create custom roles allows precise control over user permissions, improving security.
5
AdvancedRole Inheritance and Privilege Combining
🤔Before reading on: do you think assigning multiple roles to a user combines all permissions? Commit to your answer.
Concept: Users can have multiple roles, and their permissions combine to give the user all allowed actions.
When you assign multiple roles to a user, MongoDB merges all privileges from those roles. For example, if one role allows reading and another allows writing, the user can do both. Roles can also inherit from other roles, building on existing permissions.
Result
A user with roles 'read' and 'dbAdmin' can read data and manage database settings.
Understanding role inheritance and combination helps design flexible and maintainable permission structures.
6
AdvancedUser Authentication Mechanisms
🤔Before reading on: do you think MongoDB only supports username/password authentication? Commit to your answer.
Concept: MongoDB supports multiple authentication methods, including SCRAM, LDAP, and x.509 certificates.
By default, MongoDB uses SCRAM (Salted Challenge Response Authentication Mechanism) for username/password. You can also configure LDAP for centralized user management or x.509 certificates for secure connections. Users created in MongoDB must authenticate using one of these methods.
Result
Users authenticate securely before accessing the database, depending on the configured method.
Knowing authentication options helps secure MongoDB in different environments and meet organizational policies.
7
ExpertSecurity Implications of Roles and Users
🤔Before reading on: do you think giving a user 'dbAdmin' role is safe for all users? Commit to your answer.
Concept: Assigning roles must be done carefully to avoid giving excessive permissions that can lead to security risks.
Roles like 'dbAdmin' or 'userAdmin' allow powerful actions such as modifying database structure or managing users. Giving these roles to untrusted users can lead to data loss or unauthorized access. Best practice is to follow the principle of least privilege, granting only necessary permissions.
Result
Proper role assignment reduces the risk of accidental or malicious damage to the database.
Understanding the security impact of roles helps prevent common vulnerabilities and protects data integrity.
Under the Hood
MongoDB stores user information and roles in the admin database's system collections. When a user tries to connect, MongoDB checks the credentials against stored data using the configured authentication mechanism. After successful authentication, MongoDB checks the user's roles to authorize actions by matching requested operations with allowed privileges. This process happens for every command to enforce security.
Why designed this way?
Separating authentication (user identity) from authorization (permissions) allows flexible security management. Roles group permissions to avoid assigning rights individually, simplifying administration. The design supports multiple authentication methods to fit different environments and security needs.
┌───────────────┐
│ Client Login  │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Authenticate  │
│ (check user)  │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Authorize     │
│ (check roles) │
└──────┬────────┘
       │
       ▼
┌───────────────┐
│ Execute       │
│ Command       │
└───────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Can a MongoDB user do anything without assigned roles? Commit to yes or no.
Common Belief:Users can access and modify data as soon as they are created, even without roles.
Tap to reveal reality
Reality:Users without roles have no permissions and cannot perform any actions on the database.
Why it matters:Assuming users have default permissions can lead to confusion and security mistakes.
Quick: Does assigning multiple roles to a user restrict permissions to the smallest set? Commit to yes or no.
Common Belief:Multiple roles assigned to a user limit the user to only the overlapping permissions.
Tap to reveal reality
Reality:Permissions from all assigned roles combine, giving the user all allowed actions from each role.
Why it matters:Misunderstanding this can cause accidental over-permissioning and security risks.
Quick: Is it safe to give all users the 'dbAdmin' role? Commit to yes or no.
Common Belief:Giving powerful roles like 'dbAdmin' to all users is fine for convenience.
Tap to reveal reality
Reality:Powerful roles should be limited to trusted users to prevent accidental or malicious damage.
Why it matters:Over-privileged users can cause data loss or security breaches.
Quick: Does MongoDB only support username and password authentication? Commit to yes or no.
Common Belief:MongoDB only allows username and password for user authentication.
Tap to reveal reality
Reality:MongoDB supports multiple authentication methods including LDAP and x.509 certificates.
Why it matters:Ignoring other authentication methods limits security options and integration possibilities.
Expert Zone
1
Role privileges can be scoped to specific databases or collections, allowing very fine-grained access control.
2
Inherited roles can create complex permission sets that are hard to audit without careful documentation.
3
MongoDB caches user privileges during a session, so changes to roles may require user re-authentication to take effect.
When NOT to use
Avoid using broad built-in roles like 'root' or 'dbAdmin' for everyday users; instead, create custom roles with least privilege. For external user management, consider integrating LDAP or Kerberos instead of MongoDB internal users.
Production Patterns
In production, teams often create custom roles tailored to application needs, use LDAP for centralized user management, and automate user and role creation with scripts or infrastructure as code tools to maintain consistency and security.
Connections
Access Control Lists (ACLs)
MongoDB roles function similarly to ACLs by defining permissions for users.
Understanding ACLs in networking or operating systems helps grasp how MongoDB roles control access to resources.
Principle of Least Privilege (Security)
Creating users and roles in MongoDB applies the principle of least privilege by granting only necessary permissions.
Knowing this security principle guides better role design and reduces risks of over-permissioning.
Organizational Hierarchies
Role inheritance in MongoDB is like job roles in a company where higher roles include responsibilities of lower roles.
Recognizing this helps understand how permissions build up and why careful role design is important.
Common Pitfalls
#1Creating a user without assigning any roles, expecting them to access data.
Wrong approach:db.createUser({user: 'bob', pwd: 'pass123', roles: []})
Correct approach:db.createUser({user: 'bob', pwd: 'pass123', roles: [{role: 'read', db: 'testdb'}]})
Root cause:Misunderstanding that roles are required to grant permissions.
#2Assigning multiple roles but assuming permissions are limited to their intersection.
Wrong approach:db.createUser({user: 'carol', pwd: 'pass123', roles: [{role: 'read', db: 'testdb'}, {role: 'readWrite', db: 'testdb'}]}) // expecting only read permissions
Correct approach:db.createUser({user: 'carol', pwd: 'pass123', roles: [{role: 'read', db: 'testdb'}, {role: 'readWrite', db: 'testdb'}]}) // understands combined permissions
Root cause:Incorrect mental model of how role permissions combine.
#3Giving all users the 'dbAdmin' role for convenience.
Wrong approach:db.createUser({user: 'dave', pwd: 'pass123', roles: [{role: 'dbAdmin', db: 'testdb'}]}) for all users
Correct approach:Assign 'dbAdmin' only to trusted admins; others get limited roles like 'readWrite'.
Root cause:Ignoring security best practices and the principle of least privilege.
Key Takeaways
Users in MongoDB are identities that must authenticate with a username and password or other methods.
Roles define what actions users can perform and must be assigned to users to grant permissions.
Built-in roles cover common permissions, but custom roles allow precise control over access.
Assigning multiple roles combines all permissions, so be careful to avoid over-permissioning.
Following security best practices like least privilege and proper role assignment protects your data.