Hello guys!
After installing MongoDB on my machine, it's time to secure access to databases.
Change default port
In file /etc/mongod.conf in section net I changed value of port from default 27017 to 5652:
...
net:
port: 5652
...
and restarted service with the command sudo systemctl restart mongod.
Create a user with administrative rights
After I changed default port when I want to access MongoDB in console, I have to provide new port:
mongo --port 5652
After successful access, it's time to create a new user with administrative rights:
use admin
db.createUser(
{
user: "JohnDoe",
password: passwordPrompt(),
roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ]
}
)
After confirmation, I need to pass a new password for the user, all thanks to passwordPrompt. To be sure I can access MongoDB via new user, I exit and log in again with the expended command:
mongo --port 5652 -u JohnDoe -p --authenticationDatabase admin
and type in the password.
Enforcing login credentials
Once again I'm heading into /etc/mongod.conf file, where I should change security section:
...
security:
authorization: "enabled"
...
and restarted once again service with the command sudo systemctl restart mongod.
From now accessing MongoDB with authorization won't trigger any alert or access denial, but after typing in show dbs nothing will be returned. If I want to see databases, I have to authorize myself the same way after I check if my new account does work.
That was a pretty long process to secure databases. At this moment, I don't want to allow any external access to MongoDB, so it is hidden behind the firewall.
References
- https://docs.mongodb.com/manual/mongo
- https://www.digitalocean.com/community/tutorials/how-to-secure-mongodb-on-ubuntu-20-04
Cover image: Photo by Dayne Topkin on Unsplash
Top comments (0)