How to Fix MongoDB Authentication Failed Error
In this tutorial, you'll learn about How to Fix MongoDB Authentication Failed Error. We cover key concepts, practical examples, and best practices.
The Problem
You connect to MongoDB and get:
MongoServerError: Authentication failed.
Or from mongosh:
MongoNetworkError: Authentication failed
MongoDB rejected the provided credentials. The username, password, authentication database, or authentication mechanism is wrong.
Quick Fix
1. Verify the credentials
Reset the user password from the local shell (no auth required):
mongosh
use admin
db.changeUserPassword("appuser", "newSecurePassword")
Or create a new user if the old one is lost:
db.createUser({
user: "appuser",
pwd: "newSecurePassword",
roles: [{ role: "readWrite", db: "mydb" }]
})
2. Specify the correct authSource
The authentication database defaults to the database in the connection string, but users are often created in admin:
// Wrong — authSource defaults to mydb
mongoose.connect('mongodb://appuser:pass@localhost:27017/mydb')
// Right — specify admin as authSource
mongoose.connect('mongodb://appuser:pass@localhost:27017/mydb?authSource=admin')
3. Check the authentication mechanism
MongoDB 4.0+ defaults to SCRAM-SHA-256. Older drivers may expect SCRAM-SHA-1:
// Force SCRAM-SHA-1
mongoose.connect('mongodb://appuser:pass@localhost:27017/mydb?authMechanism=SCRAM-SHA-1')
4. Enable authentication in mongod.conf
If mongod is running without auth, authentication is not checked:
# /etc/mongod.conf
security:
authorization: "enabled"
Restart after changing:
sudo systemctl restart mongod
5. Check user roles
The user may exist but lack the required role:
mongosh
use admin
db.getUser("appuser")
If the user does not have the right role:
db.grantRolesToUser("appuser", [{ role: "readWrite", db: "mydb" }])
Prevention
- Always specify
authSource=adminin connection strings unless users are database-specific. - Use a password manager to generate and store MongoDB credentials.
- Create separate users per application with database-specific roles.
- Test authentication immediately after creating users.
Common Mistakes with auth failed
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad
These mistakes appear frequently in real-world MONGODB code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro