CentOS MongoDB Authentication

MongoDB is a popular NoSQL database that allows for flexible and scalable data storage. One important aspect of securing a MongoDB database is implementing authentication to prevent unauthorized access. In this article, we will cover how to set up authentication for MongoDB on a CentOS server.

Setting up MongoDB Authentication on CentOS

  1. Install MongoDB on CentOS

First, you need to install MongoDB on your CentOS server. You can follow the official MongoDB installation guide to do this.

  1. Enable Authentication in MongoDB Configuration

Once MongoDB is installed, you need to enable authentication in the MongoDB configuration file. This file is usually located at /etc/mongod.conf.

vi /etc/mongod.conf

Find the security section and uncomment the authorization line, then set the value to enabled.

security:
  authorization: enabled

Save the file and restart the MongoDB service for the changes to take effect.

sudo systemctl restart mongod
  1. Create a MongoDB User with administrative privileges

Next, you need to create a MongoDB user with administrative privileges that can be used to authenticate with the database.

Connect to the MongoDB shell by running the following command:

mongo

Switch to the admin database:

use admin

Create a new user with the necessary roles:

db.createUser(
  {
    user: "adminUser",
    pwd: "adminPassword",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)
  1. Test Authentication

To test that authentication is working correctly, exit the MongoDB shell and reconnect with the newly created user:

mongo -u adminUser -p adminPassword --authenticationDatabase admin

If you can connect successfully, authentication is working as expected.

Conclusion

In this article, we have covered how to set up authentication for MongoDB on a CentOS server. By following these steps, you can ensure that your MongoDB database is secure and protected from unauthorized access. Remember to always follow best practices for database security to keep your data safe.