Lesson 35 of 50 – MongoDB Authentication
70%

MongoDB Authentication

MongoDB authentication is the process of verifying the identity of a user or application before allowing it to access a database. It helps protect data from unauthorized access.

1. What Is Authentication?

Authentication checks whether a user has valid credentials, such as a username and password.

For example, a database administrator may have a user account:

Username: adminUser
Password: ********

MongoDB verifies the credentials when the user connects. Authentication identifies the user; authorization determines which actions that user is permitted to perform.

2. MongoDB Authentication Mechanisms

Mechanism Description
SCRAM Password-based authentication commonly used by MongoDB users.
X.509 Uses certificates to authenticate clients or members in supported configurations.
LDAP / Kerberos Enterprise authentication options available for supported MongoDB deployments.

For beginner projects, SCRAM username-and-password authentication is a useful starting point.

3. Create an Administrative User

Start MongoDB and open the MongoDB Shell using mongosh. Connect to your local server.

mongosh

Switch to the admin database:

use admin

Create a user with the userAdminAnyDatabase role:

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

The shell prompts you to enter the password without placing it directly in the command history.

Important: This role manages users across databases but does not automatically grant unrestricted read and write access to all application data. Grant only the roles needed.

4. Enable Access Control

Creating a user alone does not necessarily enable authentication on a MongoDB server. For a self-managed MongoDB deployment, enable access control in the server configuration.

Example configuration in mongod.conf:

security:
  authorization: enabled

Save the configuration and restart the MongoDB server using the appropriate service manager for your operating system.

Set up the first administrative user before enabling access control, and follow the official deployment procedure for your environment.

MongoDB Atlas manages much of the server configuration for you. In Atlas, create a database user and configure the permitted network access in the project settings.

5. Connect Using Authentication

After access control is enabled, connect with the appropriate username, password, and authentication database.

mongosh \
  "mongodb://127.0.0.1:27017/admin" \
  --username adminUser \
  --authenticationDatabase admin

Enter the password when prompted. The --authenticationDatabase admin option tells MongoDB where the user account is defined.

If the user was created in another database, specify that database as the authentication database instead.

6. Create a User for an Application

Applications should use their own database user rather than the administrative account. Create a user for the school database:

use school

db.createUser({
    user: "schoolApp",
    pwd: passwordPrompt(),
    roles: [
        { role: "readWrite", db: "school" }
    ]
})

This account receives read and write permissions on the school database. It does not need broad administrative privileges to perform ordinary student management operations.

Run this command as an account permitted to create users. If authentication is already enabled, authenticate with an appropriately privileged account first.

7. Authenticate from a Node.js Application

The MongoDB connection URI can include credentials. For this example, store the URI in an environment variable named MONGODB_URI.

const { MongoClient } = require("mongodb");

const uri = process.env.MONGODB_URI;

if (!uri) {
    throw new Error("MONGODB_URI is not configured");
}

const client = new MongoClient(uri);

async function main() {
    try {
        await client.connect();

        const db = client.db("school");
        const students = db.collection("students");

        const result = await students.find({}).toArray();

        console.log("Connected successfully.");
        console.log(result);

    } catch (error) {
        console.error("MongoDB connection failed:", error.message);
    } finally {
        await client.close();
    }
}

main();

Set MONGODB_URI to a connection string containing the application user's credentials. For example, the local URI format is:

mongodb://schoolApp:YOUR_PASSWORD@127.0.0.1:27017/school?authSource=school

Replace YOUR_PASSWORD with the actual password in your environment variable. If a username or password contains reserved URI characters, encode those characters correctly.

Do not commit passwords or connection strings containing credentials to Git or expose them in browser-side code. Use environment variables or a secrets manager.

8. Authentication vs Authorization

Authentication Authorization
Verifies identity. Determines allowed actions.
Checks credentials or certificates. Checks assigned roles and privileges.
Example: Is this user valid? Example: Can this user update students?

MongoDB uses both concepts to help protect databases. The next lesson covers authorization and roles in more detail.

9. Common Authentication Errors

  • Authentication failed: Check the username, password, and authentication database.
  • Connection refused: Confirm that the server is running and the host and port are correct.
  • Unauthorized: The account may be authenticated but lack the required role.
  • Atlas connection failure: Check the database user, IP access list, and connection URI.
  • Invalid connection URI: Check URI formatting and percent-encode reserved characters in credentials.

10. Practical Assignment

  1. Open MongoDB Shell using mongosh.
  2. Create an administrative user in the admin database.
  3. Enable access control on a test MongoDB server.
  4. Connect again using the administrative credentials.
  5. Create an application user for the school database.
  6. Connect to the database using that application user.
  7. Retrieve student records using Node.js.
  8. Test what happens when you enter an incorrect password.
  9. Explain the difference between authentication and authorization.
  10. Describe why an application should not use an administrator account.

🧠 Quick Quiz

1. What does authentication verify?




2. Which role grants read and write access to a database?




3. What does authorization determine?