pymongo.errors.OperationFailure: bad auth : authentication failed
Fixes MongoDB logins rejected for bad credentials. Use when operations raise OperationFailure bad auth. Not for TLS or network errors.
TL;DR: The username/password (or the database they authenticate against) is wrong. Double-check the password, and make sure authSource matches the database the user was created in (often admin, not your app database).
pymongo.errors.OperationFailure: bad auth : authentication failed., full error: {'ok': 0.0, 'errmsg': 'bad auth : authentication failed.', 'code': 8000, 'codeName': 'AtlasError'}Fix it
- Test the credentials with the shell: mongosh with your full Atlas connection string (it embeds your username and password). Expected: connects, proving the pair is right.
- In the URI, set authSource explicitly: your connection string with ?authSource=admin appended (keep the username, password, and host parts as they are; use whichever db holds the user). Expected: pymongo connects.
- URL-encode special characters in the password (an at-sign becomes %40). Expected: no more auth failure from a mangled password.
- Verify: client.admin.command('ping'). Expected: {'ok': 1.0}.
When this applies
- OperationFailure with errmsg bad auth : authentication failed.
When it doesn't
- TLS errors: fix certificates first.
- DNS/SRV resolution errors: the cluster hostname is wrong.
Compatibility
- pymongo 3.x/4.x; MongoDB 4.x+; Atlas.
Why it happens
MongoDB users are scoped to an authentication database. Drivers default authSource to the database in the URI path, which is usually the app database, not admin where the user was created.
Edge cases
- SCRAM-SHA-1 vs SCRAM-SHA-256: very old users may need authMechanism set explicitly.
- Rotated Atlas passwords invalidate old connection strings silently; regenerate the string from the Atlas UI.