6 min read
•Question 21 of 27hardHow do you secure a MongoDB database?
Security best practices.
What You'll Learn
- Authentication
- Authorization
- Network security
Enable Authentication
code.jsJavaScript
// Create admin user
use admin
db.createUser({
user: "admin",
pwd: "securePassword",
roles: ["root"]
});
// Create application user
use mydb
db.createUser({
user: "appUser",
pwd: "appPassword",
roles: [{ role: "readWrite", db: "mydb" }]
});Role-Based Access Control
code.jsJavaScript
// Built-in roles
// read, readWrite, dbAdmin, userAdmin, clusterAdmin, root
// Custom role
db.createRole({
role: "readWriteOrders",
privileges: [
{ resource: { db: "shop", collection: "orders" }, actions: ["find", "insert", "update"] }
],
roles: []
});
// Assign role
db.grantRolesToUser("appUser", [{ role: "readWriteOrders", db: "shop" }]);Connection String with Auth
code.jsJavaScript
// With authentication
mongoose.connect('mongodb://user:password@localhost:27017/mydb?authSource=admin');
// With SSL
mongoose.connect('mongodb://localhost:27017/mydb', {
ssl: true,
sslValidate: true,
sslCA: fs.readFileSync('/path/to/ca.pem')
});Network Security
config.ymlYAML
# mongod.conf
net:
bindIp: 127.0.0.1,10.0.0.1 # Limit to specific IPs
port: 27017
ssl:
mode: requireSSL
PEMKeyFile: /path/to/server.pemBest Practices
- Never expose MongoDB to internet
- Use strong passwords
- Enable TLS/SSL encryption
- Regularly rotate credentials
- Enable audit logging
- Keep MongoDB updated