To configure authentication in MongoDB, you need to follow these steps:
1. Create the User Administrator:
First, start the mongod without access control. \`\`\`bash mongod —port 27017 —dbpath /data/db1 \`\`\` Then, connect to the instance. \`\`\`bash mongo —port 27017 \`\`\` At the mongo prompt, add the user administrator. \`\`\`bash use admin db.createUser( { user: “myUserAdmin”, pwd: passwordPrompt(), // prompts for the password roles: [ { role: “userAdminAnyDatabase”, db: “admin” }, “readWriteAnyDatabase” ] } ) \`\`\`1. Enable Access Control:
Restart the MongoDB instance with access control. \`\`\`bash mongod —auth —port 27017 —dbpath /data/db1 \`\`\`1. Authenticate as the User Administrator:
From a mongo shell prompt, authenticate as the user administrator. \`\`\`bash mongo —port 27017 -u “myUserAdmin” -p “mypassword” —authenticationDatabase “admin“ \`\`\`1. Create Additional Users:
Once authenticated as the user administrator, you can create additional users. Switch to the database where you want to create the user. For example: \`\`\`bash use test db.createUser( { user: “myTester”, pwd: passwordPrompt(), // prompts for the password roles: [ { role: “readWrite”, db: “test” }, { role: “read”, db: “reporting” } ] } ) \`\`\`1. Connect and Authenticate as a User:
To authenticate during connection: \`\`\`bash mongo —port 27017 -u “myTester” -p “mypassword” —authenticationDatabase “test“ \`\`\` Or to authenticate after connection: \`\`\`bash use test db.auth(“myTester”, passwordPrompt()) // or cleartext password \`\`\`By following these steps, you have successfully configured the MongoDB authentication.
Source: https://docs.mongodb.com/manual/tutorial/enable-authentication/