Users and Auth

Authentication and Database Users

A mongod started the way Getting MongoDB Running started it accepts every connection and grants it everything. Closing that takes one bootstrap trick: create the first administrator while authentication is off, or over the localhost exception, which allows the first user to be created from loopback on an --auth server that has no users yet. Users belong to the database they were created in — their authentication database.

Creating an administrator and a least-privilege application userPython
db.getSiblingDB('admin').createUser({
  user: 'opsadmin', pwd: 'Str0ng-Adm1n-Pass',
  roles: [{ role: 'userAdminAnyDatabase', db: 'admin' },
          { role: 'clusterMonitor', db: 'admin' }] });
db.getSiblingDB('shop').createUser({
  user: 'api_svc', pwd: 'Str0ng-Api-Pass',
  roles: [{ role: 'readWrite', db: 'shop' }] });
const u = db.getSiblingDB('shop').getUser('api_svc');
print('mechanisms', JSON.stringify(u.mechanisms));   print('password? ', 'pwd' in u);
Output
mechanisms ["SCRAM-SHA-1","SCRAM-SHA-256"]
password?  false

No password is stored: MongoDB 1,815 keeps a SCRAM verifier, a salted iterated hash, and the handshake proves possession without sending the password. A replica set needs one thing more, because members authenticate to each other: give every member the same secret with --keyFile, 6 to 1024 base64 characters from openssl rand -base64 756. Three connections then show the outcomes to recognize.

No credentials, a wrong password, and the right one
Q="db.orders.countDocuments()"
mongosh "mongodb://127.0.0.1:28110/shop" --eval "$Q"
mongosh "mongodb://api_svc:nope@127.0.0.1:28110/shop" --eval "$Q"
mongosh "mongodb://api_svc:Str0ng-Api-Pass@127.0.0.1:28110/shop" --eval "$Q"
Output
MongoServerError: Command aggregate requires authentication
MongoServerError: Authentication failed.
5

The two failures differ, and the distinction saves time. "Requires authentication" (code Unauthorized) means no credentials were presented, or the identity presented lacks the privilege. "Authentication failed." means the SCRAM handshake failed — wrong password, unknown user, or, far more often, the right password checked against the wrong database: connecting opsadmin to mongodb://.../shop gives that message, because the driver looks for the user in shop. Add authSource=admin and it succeeds.