Agent skill
mongodb-authentication
Master MongoDB authentication methods including SCRAM, X.509 certificates, LDAP, and Kerberos. Learn user creation, role assignment, and securing MongoDB deployments.
Install this agent skill to your Project
npx add-skill https://github.com/pluginagentmarketplace/custom-plugin-mongodb/tree/main/skills/mongodb-authentication
SKILL.md
MongoDB Authentication
Secure your MongoDB with proper authentication.
Quick Start
Enable Authentication
# Start MongoDB with authentication
mongod --auth --dbpath /data/db
# Or in config file (mongod.conf)
security:
authorization: enabled
Create Admin User
// Connect to local server without auth first
const mongo = new MongoClient('mongodb://localhost:27017')
const admin = mongo.db('admin')
// Create admin user
await admin.command({
createUser: 'admin',
pwd: 'securepassword', // Or use passwordPrompt()
roles: ['root']
})
// Now restart mongod --auth
Authentication Methods
SCRAM (Salted Challenge Response)
// Default, password-based authentication
// Connection string
mongodb://username:password@localhost:27017/database
// With options
mongodb://username:password@localhost:27017/database?authSource=admin
// Create SCRAM user
db.createUser({
user: 'appuser',
pwd: 'password123',
roles: ['readWrite']
})
X.509 Certificate
// Enterprise-grade certificate authentication
// Create certificate user (External auth DB)
db.getSiblingDB('$external').createUser({
user: 'CN=client,OU=Engineering,O=Company',
roles: ['readWrite']
})
// Client connects with certificate
mongodb://USERNAME@cluster.mongodb.net/?authMechanism=MONGODB-X509&tlsCertificateKeyFile=/path/to/client.pem
LDAP
// Enterprise directory integration
// Create LDAP user (External auth DB)
db.getSiblingDB('$external').createUser({
user: 'ldapuser',
roles: ['readWrite']
})
// Configure LDAP in mongod.conf
security:
ldap:
servers: 'ldap.example.com'
authzQueryTemplate: 'dc=example,dc=com??sub?(uid={0})'
bindQueryUser: 'cn=admin,dc=example,dc=com'
bindQueryPassword: 'password'
User Management
Create User
// Basic user
db.createUser({
user: 'username',
pwd: 'password',
roles: ['readWrite']
})
// With multiple roles
db.createUser({
user: 'dbadmin',
pwd: 'password',
roles: [
{ role: 'dbAdmin', db: 'myapp' },
{ role: 'readWrite', db: 'myapp' }
]
})
// Interactive password prompt
db.createUser({
user: 'username',
pwd: passwordPrompt(),
roles: ['readWrite']
})
List Users
// Show all users in current database
db.getUsers()
// Show specific user
db.getUser('username')
Update User Password
// Change password
db.changeUserPassword('username', 'newpassword')
// Or
db.updateUser('username', {
pwd: 'newpassword'
})
Remove User
db.dropUser('username')
Built-in Roles
Database User Roles
'read' → Read-only access
'readWrite' → Read and write access
// Grant role
db.grantRolesToUser('username', ['read'])
Database Admin Roles
'dbAdmin' → Database administration
'dbOwner' → Full database access
'userAdmin' → User management
// Example
db.createUser({
user: 'dbadmin',
pwd: 'password',
roles: ['dbAdmin', 'userAdmin']
})
Cluster Admin Roles
'clusterAdmin' → Full cluster access
'clusterManager' → Cluster management
'clusterMonitor' → Read-only monitoring
// Cluster role
db.getSiblingDB('admin').createUser({
user: 'clusteradmin',
pwd: 'password',
roles: ['clusterAdmin']
})
All Built-in Roles
Admin: root, dbAdmin, userAdmin, clusterAdmin
Read: read
Write: readWrite
Backup: backup, restore
Monitoring: clusterMonitor, serverStatus, monitoring
Custom Roles
Create Custom Role
// Create custom 'reportViewer' role
db.createRole({
role: 'reportViewer',
privileges: [
{
resource: { db: 'reporting', collection: '' },
actions: ['find']
}
],
roles: []
})
// Assign to user
db.grantRolesToUser('analyst', [
{ role: 'reportViewer', db: 'admin' }
])
Privilege Structure
{
resource: {
db: 'myapp', // Database ('' = all dbs)
collection: 'users' // Collection ('' = all collections)
},
actions: [
'find', // Query documents
'insert', // Insert documents
'update', // Update documents
'remove', // Delete documents
'createIndex', // Index management
'dropIndex'
]
}
Password Policies
Strong Passwords
// Requirements for production:
// ✅ Minimum 12 characters
// ✅ Mix of uppercase, lowercase, numbers, symbols
// ✅ No dictionary words
// ✅ Not related to username
// Example strong password
// P@ssw0rd2024!MongoDB
// DON'T USE
// password, 123456, monkey, qwerty, password123
Password Rotation
// Change passwords regularly
// Monthly for service accounts
// Quarterly for normal users
// Update password
db.changeUserPassword('username', 'newpassword')
// Check user details
db.getUser('username')
Connection with Authentication
MongoDB Shell
# Connect with authentication
mongosh --username admin --password --authenticationDatabase admin mongodb://localhost:27017
# Or with connection string
mongosh 'mongodb://admin:password@localhost:27017/?authSource=admin'
Node.js Driver
const MongoClient = require('mongodb').MongoClient
// Option 1: Connection string
const client = new MongoClient(
'mongodb://username:password@localhost:27017/database?authSource=admin'
)
// Option 2: With encodeURIComponent for special chars
const user = encodeURIComponent('user@example.com')
const pass = encodeURIComponent('pass!@#$%')
const client = new MongoClient(
`mongodb://${user}:${pass}@localhost:27017/database?authSource=admin`
)
// Option 3: Auth options
const client = new MongoClient('mongodb://localhost:27017', {
auth: {
username: 'admin',
password: 'password'
},
authSource: 'admin'
})
Python PyMongo
from pymongo import MongoClient
# Connection string
client = MongoClient('mongodb://username:password@localhost:27017/database?authSource=admin')
# Or with options
client = MongoClient(
'mongodb://localhost:27017',
username='username',
password='password',
authSource='admin'
)
Security Best Practices
✅ User Management:
- Unique passwords - Each user gets own password
- Strong passwords - 12+ chars, complex
- Regular rotation - Change periodically
- Least privilege - Only needed roles
- Separate accounts - Admin vs. app users
✅ Production Security:
- Always enable auth - --auth or authorization: enabled
- Use network authentication - Bind to specific IPs
- Enable TLS/SSL - Encrypt connections
- Regular audits - Check user permissions
- Disable default users - Remove guest, test users
✅ Atlas Security:
- Enable SCRAM - Default method
- Use strong passwords - Auto-generated preferred
- Create service accounts - For applications
- Limited roles - readWrite for apps, not admin
- Monitor activity - Check who accessed what
❌ Avoid:
- ❌ Sharing passwords
- ❌ Weak passwords
- ❌ No authentication
- ❌ Admin credentials for apps
- ❌ Hardcoded passwords in code
Next Steps
- Enable authentication - On your MongoDB
- Create admin user - Initial setup
- Create app user - For application
- Test connection - From application
- Setup TLS - Encrypt connections
- Monitor users - Who can access what
Secure your MongoDB with authentication! 🔐
Recommended Agent Skills
Expand your agent's capabilities with these related and highly-rated skills.
mongodb-find-queries
Master MongoDB find queries with filters, projections, sorting, and pagination. Learn query operators, comparison, logical operators, and real-world query patterns. Use when retrieving data from MongoDB collections.
mongodb-index-creation
Master MongoDB index creation and types. Learn single-field, compound, unique, text, geospatial, and TTL indexes. Optimize query performance dramatically with proper indexing.
mongodb-atlas-setup
Master MongoDB Atlas cloud setup, cluster configuration, security, networking, backups, and monitoring. Get production-ready cloud database in minutes. Use when setting up cloud MongoDB, configuring clusters, or managing Atlas.
mongodb-replication-sharding
Master MongoDB replication, replica sets, and sharding for distributed deployments. Learn failover, shard keys, and cluster management. Use when setting up high availability or scaling horizontally.
mongodb-crud-operations
Master MongoDB CRUD operations, document insertion, querying, updating, and deletion. Learn BSON format, ObjectId, data types, and basic operations. Use when working with documents, collections, and fundamental MongoDB operations.
mongodb-indexing-optimization
Master MongoDB indexing and query optimization. Learn index types, explain plans, performance tuning, and query analysis. Use when optimizing slow queries, analyzing performance, or designing indexes.
Didn't find tool you were looking for?