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.
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.
| 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.
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.
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.
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.
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.
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.
| 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.
mongosh.admin database.school database.1. What does authentication verify?
2. Which role grants read and write access to a database?
3. What does authorization determine?