MongoDB authentication
In this post, i try to show one of the ways of using authentication on standalone versions and replica set of MongoDb
STANDALONE INSTANCE
Connect to mongo shell on the mongodb instance and run.
use admin;
db.createUser(
{
user: "adminUser",
pwd: "adminPassword",
roles: [
{ role: "userAdminAnyDatabase", db: "admin" },
"readWriteAnyDatabase"
]
}
);
REPLICA SET
On primary node, connect to mongo shell and run the command.
use admin;
db.createUser(
{
user: "adminUser",
pwd: "adminPassword",
roles: [{
role: "userAdminAnyDatabase", db: "admin" },
{ role: "dbAdminAnyDatabase", db: "admin" },
{ role: "readWriteAnyDatabase", db: "admin" },
{ role: "clusterAdmin", db: "admin" }
]
}
);
Generate a keyfile for replicaset communication. and copy this to all instances of mongodb
openssl rand -base64 756 > mongodb.key
chmod 400 mongodb.key
NOTE:
- More roles are required for replica set compared to standalone deployments.
Restart the mongod instance
- If using docker container, then run
docker run -v source:/data/db -p 27017:27017 -d mongo:latest --auth
after stopping the container. - If running standalone mongod instances, modify the config file and add these lines to it.
security:
authorization: "enabled"
keyFile: <path_to>/mongodb.key
NOTE:
- If running on docker, exec into the container and run the mongo shell.
- For production, you should secure the deployments. You can refer for that here.