MongoDB User Management
Introduction
User management is a crucial aspect of MongoDB security that allows you to control who can access your database and what actions they can perform. Proper user management helps prevent unauthorized access, data breaches, and ensures that users only have the permissions necessary for their specific tasks.
In this guide, we'll explore MongoDB's user management capabilities including creating users, assigning roles, authentication mechanisms, and best practices to maintain a secure database environment. By the end of this tutorial, you'll have a solid foundation in setting up and managing users in MongoDB.
Prerequisites
Before diving into MongoDB user management, make sure you have:
- MongoDB installed (version 4.0 or later recommended)
- Basic understanding of MongoDB concepts
- Access to a MongoDB shell (
mongosh
)
Understanding MongoDB Authentication
Authentication in MongoDB verifies the identity of a client attempting to connect to your database. By default, MongoDB starts without authentication enabled, which means anyone with network access to your database can connect and perform operations. This is convenient for development but extremely unsafe for production environments.
Enabling Authentication
Before creating users, let's first enable authentication in MongoDB:
- Start MongoDB with authentication by adding the following to your MongoDB configuration file (
mongod.conf
):
security:
authorization: enabled
- Restart your MongoDB server to apply the changes:
sudo systemctl restart mongod
Creating Your First User Administrator
Before you can create regular users, you need to create a user administrator who has privileges to manage other users.
Connect to MongoDB without authentication for this initial setup:
mongosh
Create the admin user:
use admin
db.createUser({
user: "adminUser",
pwd: "securePassword123",
roles: [{ role: "userAdminAnyDatabase", db: "admin" }]
})
Output:
{
ok: 1,
...
}
After creating the admin user, exit and reconnect with authentication:
mongosh -u adminUser -p securePassword123 --authenticationDatabase admin
Understanding MongoDB Roles
MongoDB uses a role-based access control (RBAC) system. Roles define what actions a user can perform and on which databases.
Built-in Roles
MongoDB provides several built-in roles:
-
Database User Roles:
read
: Read-only access to specified databasereadWrite
: Read and write access to specified database
-
Database Administration Roles:
dbAdmin
: Administrative tasks without data accessdbOwner
: CombinesreadWrite
,dbAdmin
, anduserAdmin
roles
-
Cluster Administration Roles:
clusterAdmin
: Highest cluster management accessclusterManager
: Management and monitoring operationsclusterMonitor
: Read-only monitoring access
-
Backup and Restoration Roles:
backup
: Ability to backup datarestore
: Ability to restore data
-
User Administration Roles:
userAdmin
: Create and modify users and roles on specific database
-
Super User Roles:
root
: Access to all operations on all resources
Creating Different Types of Users
Creating a Regular Database User
Let's create a user with read and write access to a specific database:
use myApplication
db.createUser({
user: "appUser",
pwd: "app123secure",
roles: [{ role: "readWrite", db: "myApplication" }]
})
Output:
{
ok: 1,
...
}
Creating a Read-Only User
use reporting
db.createUser({
user: "reportUser",
pwd: "report456secure",
roles: [{ role: "read", db: "reporting" }]
})
Creating a User with Multiple Database Access
use admin
db.createUser({
user: "devUser",
pwd: "dev789secure",
roles: [
{ role: "readWrite", db: "development" },
{ role: "read", db: "testing" }
]
})
Managing Existing Users
Viewing Users
To view all users in a database:
use myApplication
db.getUsers()
Output:
{
users: [
{
_id: 'myApplication.appUser',
userId: UUID('...'),
user: 'appUser',
db: 'myApplication',
roles: [ { role: 'readWrite', db: 'myApplication' } ],
mechanisms: [ 'SCRAM-SHA-1', 'SCRAM-SHA-256' ]
}
],
ok: 1
}
Updating User Roles
To grant additional roles to an existing user:
use admin
db.grantRolesToUser("devUser", [{ role: "readWrite", db: "testing" }])
To revoke roles:
use admin
db.revokeRolesFromUser("devUser", [{ role: "readWrite", db: "development" }])
Changing User Password
use admin
db.changeUserPassword("appUser", "newSecurePassword456")
Removing a User
use myApplication
db.dropUser("reportUser")
Creating Custom Roles
Sometimes the built-in roles don't match your requirements. MongoDB allows you to create custom roles:
use admin
db.createRole({
role: "analyticsRole",
privileges: [
{
resource: { db: "reporting", collection: "metrics" },
actions: ["find", "update"]
}
],
roles: [
{ role: "read", db: "reporting" }
]
})
Now you can assign this custom role to users:
use admin
db.createUser({
user: "analyticsUser",
pwd: "analytics123secure",
roles: [{ role: "analyticsRole", db: "admin" }]
})
Authentication Mechanisms
MongoDB supports several authentication mechanisms:
- SCRAM (Default): Secure, challenge-response authentication mechanism
- X.509 Certificate Authentication: Uses SSL/TLS certificates for authentication
- LDAP Authentication: Enterprise feature that integrates with LDAP servers
- Kerberos Authentication: Enterprise feature for Kerberos integration
Using SCRAM Authentication (Default)
SCRAM (Salted Challenge Response Authentication Mechanism) is the default authentication method. Users created as shown earlier automatically use SCRAM.
Using X.509 Certificate Authentication
For certificate-based authentication, first set up TLS/SSL for your MongoDB deployment, then create a user with the X.509 authentication mechanism:
use $external
db.createUser({
user: "CN=myClient,OU=myOrgUnit,O=myOrg,L=myLocality,ST=myState,C=myCountry",
roles: [
{ role: "readWrite", db: "myApplication" }
]
})
Connect using the certificate:
mongosh --tls --tlsCertificateKeyFile client.pem --tlsCAFile ca.pem
Real-World Examples
Example 1: Setting Up Users for a Web Application
For a typical web application, you might create these users:
// Admin user for overall management
use admin
db.createUser({
user: "dbAdmin",
pwd: "superSecureAdminPass123",
roles: [
{ role: "userAdminAnyDatabase", db: "admin" },
{ role: "dbAdminAnyDatabase", db: "admin" },
{ role: "readWriteAnyDatabase", db: "admin" }
]
})
// Application service user with limited access
use productionApp
db.createUser({
user: "appServiceUser",
pwd: "serviceUserPass456",
roles: [{ role: "readWrite", db: "productionApp" }]
})
// Read-only user for reporting
use productionApp
db.createUser({
user: "reportingService",
pwd: "reportingPass789",
roles: [{ role: "read", db: "productionApp" }]
})
Example 2: Database Migration Script
When setting up automation for database migrations:
// Create a migration user with temporary elevated privileges
use admin
db.createUser({
user: "migrationUser",
pwd: "tempMigrationPass",
roles: [
{ role: "readWrite", db: "productionApp" },
{ role: "dbAdmin", db: "productionApp" }
],
// Optional: Set a TTL for this user account
authenticationRestrictions: [
{
clientSource: ["192.168.1.0/24"], // Restrict from which IP range this user can connect
serverAddress: ["192.168.1.100"] // Restrict to which server address this user can connect
}
]
})
After migration:
use admin
db.dropUser("migrationUser")
Best Practices for MongoDB User Management
-
Use the Principle of Least Privilege: Grant users only the permissions they need to perform their tasks.
-
Never Use the Root User for Applications: Create specific users for each application with limited roles.
-
Use Strong Passwords: Implement a strong password policy, using long and complex passwords.
-
Regularly Audit User Access: Periodically review user accounts and their roles.
-
Remove Unused Users: Delete users that are no longer needed.
-
Implement Role Separation: Separate database administration from application access.
-
Use Authentication Restrictions: Limit from which IP addresses users can connect.
-
Rotate Credentials: Change passwords regularly, especially for privileged accounts.
-
Use Environment Variables: Store connection strings and credentials in environment variables, not in code.
-
Monitor Authentication Attempts: Track failed login attempts and suspicious activities.
Common Issues and Troubleshooting
Authentication Failed
If you get authentication errors:
- Verify the username and password are correct
- Make sure you're connecting to the correct authentication database:
// Wrong way
mongosh -u appUser -p app123secure
// Correct way - specify the authentication database
mongosh -u appUser -p app123secure --authenticationDatabase myApplication
Access Denied Errors
If a user has authentication but gets an "access denied" error:
- Check the user's roles:
use admin
db.getUser("appUser")
- Grant necessary roles if missing:
use admin
db.grantRolesToUser("appUser", [{ role: "readWrite", db: "newDatabase" }])
Visualizing User Access Flow
Summary
MongoDB's user management system provides robust controls for securing your database. By creating appropriate users with specific roles, you can ensure that every user has just the right amount of access required for their tasks.
Key concepts we've covered:
- Enabling authentication in MongoDB
- Creating and managing users with different roles
- Understanding built-in roles and creating custom roles
- Authentication mechanisms
- Best practices for user management
- Troubleshooting common issues
Implementing proper user management is a fundamental step in securing your MongoDB deployment. When combined with other security measures like encryption and network security, it forms a comprehensive security strategy for your data.
Additional Resources
Exercises
- Create a user with read-only access to a
customers
database but read-write access to aproducts
database. - Create a custom role that allows a user to insert and find documents, but not update or delete them.
- Set up a database administrator user with full access to a specific database but no access to other databases.
- Create a user with time-limited credentials that expire after 7 days.
- Implement IP-based restrictions on a user account that can only connect from specific IP addresses.
If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)