- Edit the MongoDB configuration file: First, edit the MongoDB configuration file (typically
mongod.conf) to enable authentication. Add or modify the following lines in the configuration file:
yamlsecurity: authorization: enabled
- Restart the MongoDB service: After updating the configuration file, restart the MongoDB service to apply the changes. Use one of the following commands:
bashsudo service mongod restart
or:
bashsudo systemctl restart mongod
- Create an administrator user: After enabling authentication, create at least one user with administrative privileges. Connect to the database using the MongoDB command-line interface
mongoand execute the following command to create the administrator user:
javascriptuse admin db.createUser({ user: "admin", pwd: "your_secure_password", roles: [{ role: "userAdminAnyDatabase", db: "admin" }] })
- Verify administrator login: After creating the administrator user, log in with this user to confirm that authentication is properly configured. Use the following command:
bashmongo -u admin -p your_secure_password --authenticationDatabase admin
- Create users for application databases: Create additional users for different databases as required, each with specific roles and permissions. For instance, create a user with read and write permissions for a database named
mydatabase:
javascriptuse mydatabase db.createUser({ user: "appUser", pwd: "another_secure_password", roles: [{ role: "readWrite", db: "mydatabase" }] })
Following these steps enables authentication in MongoDB to enhance database security. Handle each operation carefully, using complex and secure passwords to prevent unauthorized access.