Skip to content
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 to admin but 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 --auth and 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=admin

4. 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 mongod

FAQ

What is the 'localhost exception' in MongoDB?
If no users exist in MongoDB, you can connect from the local machine without authentication to create the first user. Once a user is created, authentication is enforced. This is called the localhost exception.
What is authSource and why does it matter?
authSource specifies which database holds the user credentials. If not provided, MongoDB defaults to the database in the connection string. If your user was created in admin, set authSource=admin in the URI.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro