Introduction

Authentication failures in MongoDB occur when the provided credentials cannot be validated against the configured authentication mechanism. This commonly happens after fresh installations, user migrations, or when switching between authentication methods. Understanding the authentication flow is crucial for resolving these errors efficiently.

Symptoms

Authentication errors appear with various error codes:

text
Error: Authentication failed.
MongoError: Authentication failed.
Error: unable to authenticate using mechanism SCRAM-SHA-256
Error: AuthenticationFailed: Authentication failed
MongoServerError: Authentication failed, username not found
Error: SASL authentication failed

In MongoDB logs (/var/log/mongodb/mongod.log):

text
{"t":{"$date":"2026-04-03T10:15:30.123Z"},"s":"I","c":"ACCESS","id":20249,"msg":"Authentication failed","attr":{"mechanism":"SCRAM-SHA-256","principalName":"myuser","authenticationDatabase":"admin","result":18}}

Error code 18 indicates wrong password; code 11 indicates user not found.

Common Causes

  1. 1.Incorrect username or password - Simple credential mismatch
  2. 2.Wrong authentication database - User created in admin but connecting to different DB
  3. 3.SCRAM version mismatch - Server using SCRAM-SHA-256, client sending SCRAM-SHA-1
  4. 4.User not created - Attempting to authenticate with non-existent user
  5. 5.Authentication disabled - Connecting with credentials to server without auth enabled
  6. 6.Special characters in password - Unescaped characters in connection string

Step-by-Step Fix

Step 1: Check Authentication is Enabled

Verify MongoDB has authentication enabled:

```bash mongosh --host localhost --port 27017

# Check authentication settings db.serverStatus().security ```

In mongod.conf, authentication should be:

yaml
security:
  authorization: enabled

If authorization is disabled, you can connect without auth and fix users.

Step 2: List Existing Users

Connect without authentication (if possible) or with admin user:

```javascript // Switch to admin database use admin

// List all users db.system.users.find({}, {user: 1, db: 1, mechanisms: 1})

// Or more detailed db.getUsers() ```

Step 3: Verify User Authentication Database

Users authenticate against the database where they were created:

```javascript // User created in admin database use admin db.auth("myuser", "password")

// User created in mydb database use mydb db.auth("myuser", "password") ```

Connection string must specify authSource:

text
mongodb://myuser:password@localhost:27017/mydb?authSource=admin

Step 4: Check and Fix SCRAM Mechanism

Check supported mechanisms:

javascript
use admin
db.getUser("myuser").mechanisms
// Output: [ "SCRAM-SHA-256", "SCRAM-SHA-1" ]

Create or update user with correct mechanisms:

```javascript use admin

// Create new user with both SCRAM mechanisms db.createUser({ user: "appuser", pwd: "securePassword123", roles: [{ role: "readWrite", db: "myapp" }], mechanisms: ["SCRAM-SHA-256", "SCRAM-SHA-1"] })

// Update existing user mechanisms db.updateUser("appuser", { mechanisms: ["SCRAM-SHA-256", "SCRAM-SHA-1"] }) ```

Step 5: Reset Password if Needed

If password is unknown or corrupted:

javascript
use admin
db.changeUserPassword("appuser", "newSecurePassword123")

Step 6: Handle Special Characters

Escape special characters in connection strings:

bash
# Password with special chars: p@ss#word!
# URL encode special characters
mongosh "mongodb://appuser:p%40ss%23word%21@localhost:27017/mydb?authSource=admin"

Common URL encodings: - @%40 - #%23 - /%2F - :%3A - !%21

Verification

Test authentication after fixes:

```bash # Test with mongosh mongosh --username appuser --password --authenticationDatabase admin

# Test connection string mongosh "mongodb://appuser:password@localhost:27017/mydb?authSource=admin"

# Verify in MongoDB use admin db.runCommand({connectionStatus: 1}) ```

Check successful authentication in logs:

text
{"msg":"Authentication succeeded","attr":{"mechanism":"SCRAM-SHA-256","principalName":"appuser"}}

Common Pitfalls

  • Connecting to wrong database - Always specify authSource for users in admin
  • Driver version mismatch - Older drivers may default to SCRAM-SHA-1
  • Copy-paste errors - Hidden characters in passwords from copy-paste
  • Case sensitivity - MongoDB usernames are case-sensitive
  • Expired certificates - For x.509 authentication, check cert validity

Best Practices

  • Store credentials in environment variables, not connection strings
  • Use the most secure authentication mechanism available (SCRAM-SHA-256)
  • Create application-specific users with minimal required roles
  • Document which database each user was created in
  • Rotate passwords regularly using automated tools
  • MongoDB Connection Refused
  • MongoDB SCRAM Authentication Failed
  • MongoDB LDAP Authentication Timeout
  • MongoDB x.509 Certificate Auth Failed