In this tutorial, we will cover the steps to set up authentication and authorization for MongoDB on Amazon Web Services (AWS) EC2. We will use MongoDB Community Edition, which is a free and open-source database system.
Prerequisites:
- An AWS account
- An EC2 instance running the MongoDB Community Edition
- An SSH client, such as PuTTY or Terminal (for Mac/Linux)
- Basic knowledge of MongoDB
Step 1: Connecting to the EC2 Instance
Use your SSH client to connect to the EC2 instance using the public IP address and the private key and install MongoDB using the following commands:
sudo yum update -y
sudo vi /etc/yum.repos.d/mongodb-org-4.4.repo
Add the following lines to the repo file:
[mongodb-org-4.4]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/amazon/2/mongodb-org/4.4/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-4.4.asc
Save and exit the file, then run mongo
to enter the MongoDB Shell.Then type use admin
to switch to the admin database. Create an administrative user with the following command:
db.createUser({user: "[username]", pwd: "[password]", roles: [{role: "root", db: "admin"}]})
Finally, exit the shell by typing exit
Step 3: Enabling Authentication and Authorization
Edit the MongoDB configuration file by running the following command:
sudo vi /etc/mongod.conf
Add the following lines to the file:
security:
authorization: enabled
Save and exit the file, then restart the MongoDB service by running the following command:
sudo service mongod restart
Step 4: Testing the Authentication and Authorization
Connect to the MongoDB shell by running the following command:
mongo --username [username] --password [password] --authenticationDatabase admin
Switch to a non-admin database by running use [database name]
Create a new user with restricted privileges by running the following command:
db.createUser({user: "[username]", pwd: "[password]", roles: [{role: "readWrite", db: "[database name]"}]})
Exit the MongoDB shell by typing exit
Step 5: Updating the Application Connection String
Modify the connection string in the application to include the username and password:
mongodb://[username]:[password]@[EC2 public IP]:27017/[database name]
Test the application to ensure that authentication and authorization are working correctly.
In this tutorial, we have covered the steps to set up authentication and authorization for MongoDB on AWS EC2. By enabling authentication and authorization, you can secure your MongoDB database and protect it from unauthorized access.
Skip the hassle and launch a fully configured and containerized MongoDB instance with web administration on AWS Marketplace: