Enable authentication in MongoDB
20 February 2025 · 2 min read
mongodb · authentication · tech · accessControll · database

20 February 2025 · 2 min read
mongodb · authentication · tech · accessControll · database

In today's data-driven world, security is paramount. If you're using MongoDB, ensuring that your data is protected from unauthorized access is crucial. By default, MongoDB installations often run without authentication, leaving them vulnerable. This blog post will walk you through the essential steps to enable authentication and secure your MongoDB database.
mongo (older version) or mongosh (newer version of mongoshell) shell and creating a user with the necessary roles (e.g., userAdminAnyDatabase or root).mongosh//
test> use admin
switched to db admin
admin> db.createUser(
{
user: "yourAdminUserName",
pwd: "yourPassword",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
# the response looks like this
{ ok: 1 }
admin>admin> exit//
/etc/mongod.conf in Linux and Mac).security section, add or modify the authorization setting to enabledsecurity:
authorization: enabledsudo systemctl restart mongod.service//
mongosh -u username -pEnabling authentication is a fundamental step in securing your MongoDB database. By following these steps and adhering to best practices, you can protect your valuable data from unauthorized access.