This guide covers essential MongoDB security concepts commonly asked in technical interviews. Each question includes detailed answers and practical examples.
MongoDB provides several security features:
Authentication implementation involves several steps:
// Create admin user
db.createUser({
user: "adminUser",
pwd: "securePassword",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
})
// Create application user
db.createUser({
user: "appUser",
pwd: "appPassword",
roles: [
{ role: "readWrite", db: "myapp" },
{ role: "read", db: "reports" }
]
})
// Enable authentication
security:
authorization: enabled
// SCRAM-SHA-256 authentication
mongod --auth --setParameter authenticationMechanisms=SCRAM-SHA-256
// LDAP authentication
mongod --auth --setParameter authenticationMechanisms=PLAIN,SCRAM-SHA-256
// X.509 certificate authentication
mongod --tlsMode requireTLS --tlsCertificateKeyFile /etc/ssl/mongodb.pem
RBAC implementation involves defining roles and permissions:
// Create custom role
db.createRole({
role: "appAdmin",
privileges: [
{
resource: { db: "myapp", collection: "" },
actions: [ "find", "update", "insert", "remove" ]
},
{
resource: { db: "myapp", collection: "users" },
actions: [ "find" ]
}
],
roles: []
})
// Assign role to user
db.grantRolesToUser(
"appUser",
[ { role: "appAdmin", db: "myapp" } ]
)
// View user roles
db.getUser("appUser")
// Update role privileges
db.updateRole(
"appAdmin",
{
privileges: [
{
resource: { db: "myapp", collection: "orders" },
actions: [ "find", "update" ]
}
]
}
)
// Revoke role
db.revokeRolesFromUser(
"appUser",
[ { role: "appAdmin", db: "myapp" } ]
)
Encryption implementation involves multiple layers:
// Enable encryption at rest
mongod --enableEncryption --encryptionKeyFile /path/to/keyfile
// Configure TLS/SSL
mongod --tlsMode requireTLS --tlsCertificateKeyFile /etc/ssl/mongodb.pem
// Field-level encryption
const client = new MongoClient(uri, {
autoEncryption: {
keyVaultNamespace: "encryption.__keyVault",
kmsProviders: {
local: {
key: masterKey
}
},
schemaMap: {
"myapp.users": {
bsonType: "object",
properties: {
ssn: {
encrypt: {
bsonType: "string",
algorithm: "AEAD_AES_256_CBC_HMAC_SHA_512_Deterministic"
}
}
}
}
}
}
})
Follow these security best practices:
// Secure configuration
security:
authorization: enabled
clusterAuthMode: x509
javascriptEnabled: false
redactClientLogData: true
net:
ssl:
mode: requireSSL
PEMKeyFile: /etc/ssl/mongodb.pem
CAFile: /etc/ssl/ca.pem
auditLog:
destination: file
format: JSON
path: /var/log/mongodb/audit.log
// Enable security auditing
db.adminCommand({
setParameter: 1,
auditAuthorizationSuccess: true
})
// Monitor authentication attempts
db.system.profile.find({
"command.authenticate": { $exists: true }
})
// Check user activities
db.system.profile.find({
"command.find": { $exists: true }
}).sort({ millis: -1 })
Continue your MongoDB interview preparation with: