18
MongoDBERRORNotableAuthenticationHIGH confidence

Authentication failed due to incorrect credentials

What this means

This error indicates that the username and password combination provided during a connection attempt is incorrect. The user exists, but the credentials do not match what is stored in the authentication database.

Why it happens
  1. 1Providing the wrong password for a valid username
  2. 2A typo in the password field of the connection string
  3. 3Using old credentials after a password has been recently changed
  4. 4Special characters in a password not being properly URL-encoded in the connection string
How to reproduce

A client attempts to connect using a valid username but an incorrect password.

trigger — this will error
trigger — this will error
// Assuming user 'app_user' has a different password.
// Connection attempt from a driver (e.g., Python):
client = pymongo.MongoClient("mongodb://app_user:wrong_password@localhost:27017/?authSource=admin")
client.admin.command('ping')

expected output

pymongo.errors.OperationFailure: Authentication failed.

Fix 1

Verify and Correct the Password

WHEN Authentication fails for a known user.

Verify and Correct the Password
// Ensure the password in your configuration or secret manager is correct.
const connectionString = "mongodb://app_user:the_correct_password@host...";

Why this works

The most direct fix is to check and update the password in the application's configuration. Ensure there are no typos or encoding issues.

Fix 2

Reset the User's Password

WHEN The password is lost or unknown.

Reset the User's Password
// Connect as an admin user first
use admin
db.updateUser("app_user", {
  pwd: passwordPrompt()
})

Why this works

If the password is truly forgotten, an administrative user can reset it using the `updateUser` command.

Fix 3

Properly Encode Special Characters in URI

WHEN The password contains characters like '@', ':', '/', or '%'.

Properly Encode Special Characters in URI
// Example: password is "p@ss:word"
// Manually encoded: "p%40ss%3Aword"
const encodedPass = encodeURIComponent("p@ss:word");
const connectionString = "mongodb://app_user:" + encodedPass + "@host...";

Why this works

Passwords in a MongoDB connection string must be URL-encoded. Most drivers and libraries offer a utility to do this automatically.

What not to do

Store database credentials in plaintext in source code

This is a major security vulnerability. Use environment variables, a secrets management system (like HashiCorp Vault or AWS Secrets Manager), or other secure configuration methods.

Sources
Official documentation ↗

mongodb/mongo src/mongo/base/error_codes.yml

Connection String URI Format

Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev

← All MongoDB errors