Error
Error Code: 18

MongoDB Error 18: Authentication Failed

📦 MongoDB
📋

Description

This error indicates that the MongoDB server rejected a connection attempt due to invalid authentication credentials. It commonly occurs when a client tries to connect to a MongoDB instance with an incorrect username, password, or an unauthorized user.
💬

Error Message

Authentication Failed
🔍

Known Causes

4 known causes
⚠️
Incorrect Username or Password
The provided username or password does not match any existing user's credentials on the MongoDB server.
⚠️
User Does Not Exist
The specified user account has not been created or does not exist in the authentication database.
⚠️
Incorrect Authentication Database
The client is attempting to authenticate against a database different from where the user account was defined or authorized.
⚠️
Authentication Mechanism Mismatch
The client and server are configured to use different authentication mechanisms (e.g., SCRAM-SHA-1 vs. SCRAM-SHA-256), leading to a handshake failure.
🛠️

Solutions

5 solutions available

1. Verify Credentials easy

Check username and password are correct

1
Test connection
mongosh --host localhost -u username -p password --authenticationDatabase admin
2
Reset password if forgotten
// Connect as admin
use admin
db.changeUserPassword("username", "newpassword")

2. Check Authentication Database easy

User might be in different database

1
Find user in system
use admin
db.system.users.find({ user: "myuser" })
2
Specify correct authSource
// If user is in 'admin' database:
mongosh "mongodb://user:pass@host/mydb?authSource=admin"

// If user is in 'mydb' database:
mongosh "mongodb://user:pass@host/mydb?authSource=mydb"

3. Check Authentication Mechanism medium

Ensure client uses correct auth method

1
Check server auth mechanism
db.adminCommand({ getParameter: 1, authenticationMechanisms: 1 })
2
Specify mechanism in connection
mongosh "mongodb://user:pass@host/db?authMechanism=SCRAM-SHA-256"

4. Create Missing User easy

User might not exist

1
Create user
use admin
db.createUser({
  user: "newuser",
  pwd: "password",
  roles: [{ role: "readWrite", db: "mydb" }]
})

5. Fix Connection String Encoding easy

Special characters need URL encoding

1
URL encode special characters in password
// If password is: p@ss:word/123
// Encode as: p%40ss%3Aword%2F123

mongosh "mongodb://user:p%40ss%3Aword%2F123@host/db"
2
Common encodings
// @ = %40
// : = %3A
// / = %2F
// # = %23
// ? = %3F
🔗

Related Errors

5 related errors