Authentication ensures that only authorized users and applications can access your MongoDB database.
By default, MongoDB allows access without authentication, which is a major security risk in production. You should always enable authentication to ensure only authorized users can connect to the database.
--auth
flag when starting the MongoDB server:bashCopy codemongod --auth --dbpath /path/to/db
mongod.conf
file:yamlCopy codesecurity: authorization: enabled
mongo use admin db.createUser({ user: "admin", pwd: "yourAdminPassword", // Choose a strong password roles: [{ role: "root", db: "admin" }] })
db.createUser({ user: "myappUser", pwd: "myAppPassword", roles: [{ role: "readWrite", db: "myappDB" }] })
MongoDB supports several authentication mechanisms:
For most use cases, SCRAM-SHA-256 will suffice.
Authorization ensures that users have the appropriate permissions to access and perform actions on resources like databases, collections, and documents.
MongoDB provides a role-based access control (RBAC) system to assign specific roles to users.
read
: Grants read access to a database.readWrite
: Grants read and write access to a database.dbAdmin
: Grants administrative access to a database.userAdmin
: Grants user management permissions.root
: Superuser role with full access to all databases.db.createRole({ role: "customRole", privileges: [ { resource: { db: "myappDB", collection: "" }, actions: [ "find", "insert", "update" ] } ], roles: [] })
Always grant the minimum necessary permissions. For example, avoid giving write permissions if the user only needs read access. Always use the least privileged roles necessary for the task.
Data encryption ensures that sensitive data is protected both at rest (when stored in the database) and in transit (when being sent over the network).
To encrypt data in transit (between the client application and the MongoDB server), you need to enable TLS/SSL encryption.
openssl req -new -newkey rsa:2048 -days 365 -nodes -keyout mongodb.key -out mongodb.csr openssl x509 -req -in mongodb.csr -signkey mongodb.key -out mongodb.crt
mongod.conf
to enable SSL:yamlCopy codenet: ssl: mode: requireSSL PEMKeyFile: /path/to/mongodb.crt PEMKeyPassword: your_key_password
ssl
option:javascriptCopy codemongoose.connect('mongodb://username:password@localhost:27017/myappDB', { ssl: true, sslValidate: true, sslCA: '/path/to/ca.pem', });
MongoDB Enterprise offers Encryption at Rest using WiredTiger encryption. Encryption at rest ensures that data is encrypted when stored on disk.
mongod.conf
:yamlCopy codestorage: encryption: enabled: true keyFile: /path/to/your/keyfile
Backup is critical for data protection, and MongoDB offers several backup solutions.
mongodump
command to create a backup of your database.bashCopy codemongodump --uri="mongodb://username:password@localhost:27017/myappDB" --out=/path/to/backup
Ensure that your backups are encrypted, especially if they contain sensitive data. You can use encrypted filesystems or external encryption tools like AWS KMS (Key Management Service).
MongoDB Enterprise supports auditing, which tracks all activities and changes made in the database. This is essential for monitoring suspicious activities and for compliance with regulatory standards.
In your mongod.conf
, you can enable auditing:
yaml
Copy code
auditLog: destination: file format: BSON path: /var/log/mongodb/audit.log
This will log all operations, including authentication events, data access, and administrative actions.
SQL Injection-style attacks are not as common with MongoDB as with SQL databases, but NoSQL injection is still a concern. To prevent injection attacks:
Always use Mongoose methods and avoid using raw queries with string concatenation.
Unsafe:
javascript
Copy code
User.find({ name: req.query.name }); // Potential for NoSQL injection
Safe:
javascript
Copy code
User.find({ name: { $eq: req.query.name } }); // Ensures proper query formatting
Validate and sanitize inputs to avoid malicious content.
express-validator
to sanitize user inputs:javascriptCopy codeconst { body, validationResult } = require('express-validator'); app.post('/user', [ body('email').isEmail().normalizeEmail(), body('age').isInt({ min: 18, max: 120 }), ], (req, res) => { const errors = validationResult(req); if (!errors.isEmpty()) { return res.status(400).json({ errors: errors.array() }); } // Proceed with creating the user });
bindIp
option in the mongod.conf
:yamlCopy codenet: bindIp: 127.0.0.1 # Limit access to localhost
$where
queries) if not needed:yamlCopy codesecurity: javascriptEnabled: false