Authentication failed due to incorrect credentials
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.
- 1Providing the wrong password for a valid username
- 2A typo in the password field of the connection string
- 3Using old credentials after a password has been recently changed
- 4Special characters in a password not being properly URL-encoded in the connection string
A client attempts to connect using a valid username but an incorrect password.
// 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.
// 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.
// 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 '%'.
// 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.
✕ 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.
Content generated with AI assistance and reviewed for accuracy. Found an error? hello@errcodes.dev