This tutorial aims to guide you through the process of setting up user authentication in MongoDB. User authentication is a critical security feature that protects your data by ensuring only authorized users can access specific resources.
What you will learn:
Prerequisites:
User authentication in MongoDB is implemented via role-based access control. Here, we will create a new user with a specific role and then configure MongoDB to require authentication.
Start the MongoDB instance without access control to create new users.
mongod --port 27017 --dbpath /data/db1
Connect to the MongoDB instance that you have started.
mongo --port 27017
In the admin database, add a user with the userAdminAnyDatabase role.
use admin
db.createUser(
{
user: "adminUser",
pwd: "adminPassword",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
Here are some examples that show how to create users with different roles.
use records
db.createUser(
{
user: "recordsUser",
pwd: "recordsPassword",
roles: [
{ role: "readWrite", db: "records" }
]
}
)
In the above example, we first switch to the records
database using use records
. We then create a new user named recordsUser
with the password recordsPassword
and assign the readWrite
role to the user on the records
database.
use admin
db.createUser(
{
user: "readUser",
pwd: "readPassword",
roles: [
{ role: "readAnyDatabase", db: "admin" }
]
}
)
In this tutorial, we learned how to set up user authentication in MongoDB. We looked at how to create users with specific roles and permissions and how to configure MongoDB to require authentication.
Here are some exercises for you to try:
Solutions:
use admin
db.createUser(
{
user: "doubleDBUser",
pwd: "doubleDBPassword",
roles: [
{ role: "readWrite", db: "records" },
{ role: "readWrite", db: "inventory" }
]
}
)
use admin
db.createUser(
{
user: "writeUser",
pwd: "writePassword",
roles: [
{ role: "writeAnyDatabase", db: "admin" }
]
}
)
For further practice, try creating users with different combinations of roles and permissions.