MongoDB "Authentication failed" (SCRAM) with MONGODB_URI in CI
The server rejected the SCRAM handshake: the credentials in your connection string did not match a user. The network is fine; the username, password, or authSource is wrong or not injected.
What this error means
The driver throws "MongoServerError: Authentication failed" right after connecting, once it tries to authenticate with the credentials from MONGODB_URI.
MongoServerError: Authentication failed.
at Connection.onMessage (/app/node_modules/mongodb/lib/cmap/connection.js:229:30) {
code: 18,
codeName: 'AuthenticationFailed'
}Common causes
The password secret is empty or wrong
The CI secret holding the password is unset or stale, so the URI carries no valid credentials and SCRAM fails.
The wrong authSource database
The user lives in admin (or a specific db) but the URI omits or misnames authSource, so the server checks the wrong database.
How to fix it
Build the URI from injected secrets with authSource
- Store the username and password as CI secrets.
- Compose the URI including
authSourcefor the database that holds the user. - URL-encode any special characters in the password.
env:
MONGODB_URI: mongodb://${{ secrets.MONGO_USER }}:${{ secrets.MONGO_PASS }}@localhost:27017/appdb?authSource=adminVerify the user exists in the expected db
Confirm the credentials authenticate against the intended authSource before running tests.
mongosh "$MONGODB_URI" --eval 'db.runCommand({connectionStatus:1})'How to prevent it
- Inject credentials from secrets, never hardcode them in the URI.
- Set
authSourceto the database that owns the user (often admin). - URL-encode special characters in passwords.