Photo by chansu shin on Unsplash

On this page

This chapter follows Installing and connecting to MongoDB.

Authentication answers who is connecting. Authorization answers what that identity may read or write. MongoDB enables both together: without a valid user, most commands fail once authorization is enforced.

SCRAM and user records

Modern deployments use SCRAM (Salted Challenge Response Authentication Mechanism) for password verification. User documents live in the system.users collection of the database where they were created—often admin for administrative users, or an application database for least-privilege app accounts.

You can connect anonymously to mongosh on a fresh local instance, but as soon as --auth is enabled (or Atlas enforces users), operations require credentials:

Terminal window
mongosh "mongodb://dev:devpass@localhost:27017/admin"

If auth is on and you omit credentials, reads that need privilege return MongoServerError: command find requires authentication.

Built-in roles

Roles bundle privileges. Common built-in roles:

Role Scope Typical use
read One database Read-only services
readWrite One database Application CRUD
dbAdmin One database Index management, stats
userAdmin One database Create users on that DB
readAnyDatabase Cluster Monitoring (admin DB only)
root Cluster Full admin (avoid in apps)

Atlas maps the same role names when you create Database Access users. Prefer readWrite on a single application database instead of root in production.

Create an application user

After authenticating as an admin user:

Terminal window
mongosh "mongodb://dev:devpass@localhost:27017/admin"
use myapp
db.createUser({
user: 'app',
pwd: passwordPrompt(),
roles: [{ role: 'readWrite', db: 'myapp' }],
})

Connection string for the app:

Terminal window
mongodb://app:YOUR_PASSWORD@localhost:27017/myapp?authSource=myapp

authSource must be the database where the user document was stored—here myapp, not admin.

Docker bootstrap credentials

When you pass MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD to the official image, MongoDB creates a root user in admin on first startup. Use that only for administration; create scoped users for applications.

Terminal window
docker run --name mongo-dev -p 27017:27017 \
-e MONGO_INITDB_ROOT_USERNAME=dev \
-e MONGO_INITDB_ROOT_PASSWORD=devpass \
-d mongodb/mongodb-community-server:8.0-ubuntu2204

Connect from TypeScript with credentials

Never hard-code passwords. Pass the full URI via environment variable as in the install chapter:

src/db/client.ts
import { MongoClient } from 'mongodb';
const uri = process.env.MONGODB_URI;
if (!uri) throw new Error('MONGODB_URI is not set');
export const client = new MongoClient(uri);

Atlas URIs include TLS and SRV resolution:

Terminal window
MONGODB_URI="mongodb+srv://app:PASSWORD@cluster0.xxxxx.mongodb.net/myapp?retryWrites=true&w=majority"

Rotate passwords in Atlas under Database Access; update the secret store your app reads from, then rolling-restart workers.

Authorization failures in applications

When a user lacks privilege, the driver throws MongoServerError with code 13 (Unauthorized). Log the command name and collection, not the password. Integration tests should use a dedicated user with readWrite on a throwaway database.

Next: CRUD operations in MongoDB.

Search articles

Type a word to search published articles.

Open the search page