Skip to main content

Authentication

Before we dive into the topic of authentication in MongoDB, let's start with understanding what authentication is. Authentication is the process of verifying the identity of a user, device, or system. It is a crucial aspect of security as it ensures that only authorized and authenticated users have access to your MongoDB databases.

Enabling Authentication

By default, MongoDB runs without authentication, allowing any user to connect and perform operations. To enforce authentication, you need to start the MongoDB server with the --auth option.

Here's an example:

mongod --auth --port 27017 --dbpath /data/db

After starting MongoDB with the --auth option, you need to connect to the instance as an administrator and create the first user. This user should have privileges across all databases.

Creating the First User

The first user you create should be an administrative user with the ability to manage user access. Here's an example of how to create a user:

mongo --port 27017

In the mongo shell, switch to the admin database:

use admin

And then create the user:

db.createUser(
{
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)

Authenticating as a User

Once the user is created, you can authenticate as that user using the db.auth() method. Here's how to do it:

use admin
db.auth("myUserAdmin", "abc123")

Built-In Roles

MongoDB provides built-in roles that grant a variety of privileges. Some of the most commonly used roles are:

  • read: Allows read-only access to the database.
  • readWrite: Allows read and write access to the database.
  • dbAdmin: Allows administrative access to the database.
  • userAdmin: Allows management of user access to the database.
  • clusterAdmin: Provides the greatest cluster-wide access.

Creating Additional Users

After creating an administrative user, you can use that user to create additional users and grant them specific roles and permissions.

Here's an example of how to create a user with read and write access to a specific database:

use myDatabase
db.createUser(
{
user: "myDatabaseUser",
pwd: "abc123",
roles: [ { role: "readWrite", db: "myDatabase" } ]
}
)

Conclusion

That's the basics of authentication in MongoDB. By understanding and implementing authentication, you can greatly enhance the security of your MongoDB databases. Remember, maintaining the security of your data should always be a priority. Practice creating users and assigning roles to understand how permissions work in MongoDB.