MongoDB: Authentication failed
MongoDB: Authentication failed
DodaTech
2 min read
The error “MongoDB: Authentication failed” (or MongoServerError: Authentication failed) means the credentials your application provided do not match any user in MongoDB’s authentication system.
What It Means
MongoDB supports role-based access control through the admin database’s user collection. When a client connects and issues an authenticate command, MongoDB checks the username, password, and authentication database. If any field is wrong, the connection is rejected.
Why It Happens
- The username or password is incorrect in the connection string.
- The
authSource(authentication database) is wrong — defaults toadminbut your user may be defined in another database. - The user was created without the correct role or in the wrong database.
- MongoDB is running without
--authand you added credentials but never enabled authentication. - The user was dropped or the database was recreated.
- The SCRAM-SHA-1 or SCRAM-SHA-256 hash is corrupted.
How to Fix It
1. Reset the user password via the localhost exception
mongosh
use admin
db.changeUserPassword('youruser', 'NewStrongPassword123!')2. Verify the user exists with correct roles
mongosh admin -u root -p
use admin
db.getUser('youruser')3. Specify the correct authSource in your connection string
mongodb://youruser:password@localhost:27017/mydb?authSource=admin4. Create a new user if needed
mongosh admin -u root -p
use mydb
db.createUser({
user: 'appuser',
pwd: 'StrongPassword123!',
roles: [{ role: 'readWrite', db: 'mydb' }]
})5. Enable authentication if not already enabled
# In /etc/mongod.conf
security:
authorization: enabled
sudo systemctl restart mongodFAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro