Y NOT — Authenticate and Authorize MongoDB
In this article, we would see the steps to enable authentication and authorization on MongoDB. Authentication and authorization might sound similar, but they are distinct security processes in the world of identity and access management (IAM).
Authentication vs Authorization:
- Authentication is the act of validating that users are whom they claim to be. This is the first step in any security process.
- Authorization in a system security is the process of giving the user permission to access a specific resource or function.
- In secure environments, authorization must always follow authentication.
- Users should first prove that their identities are genuine before an organization’s administrators grant them access to the requested resources.
Create Users and Assign Roles/Privileges On MongoDB:
- After successful installation and launch of Mongod (Mongo server), one of the ways to interact with Mongo Server is via Mongo CLI Client.
- Below command is used to create a new user with authentication protocol (in the form of username & password) and also assign respective role privileges (for authorization)
userdb.createUser ({
user: “adminuser”
pwd: “******”
roles: [{ role: “userAdminAnyDatabase”, db: “admin” }, “readWriteAnyDatabase”]
})
- It creates a new user ‘adminuser’ on admin database which has admin access to any database.
- Similar way, below command creates a new user ‘user-01’ on userdb database which assigns Read & Write privileges only on userdb database.
db.createUser ({
user: “user-01”,
pwd: “****”,
roles: [{ role: “readWrite”, db: “userdb” }]
})
Restart MongoD (Mongo Server) with Authentication:
- Step 1 — Execute db.shutdownServer() command on MongoDB CLI to kill the current MongoDB Process.
- Step 2 — Execute mongod --remove command on your terminal to remove Mongod
- Step 3 — Execute below command to start Mongod (Mongo Server) with authentication enabled.
mongod — dbpath “C:\Program Files\MongoDB\Server\4.2\data” — logpath “C:\Program Files\MongoDB\Server\4.2\log\mongod.log” — auth — install — serviceName “MongoDB”
- Step 4 — Execute net start MongoDB command to start the Mongo DB Service. Verify if the process got successfully started by using ps -ef in case of linux or tasklist /FI “IMAGENAME eq mongod.exe” in case of windows based machine.
- Step 5 — Use mongo — port 27017 — authenticationDatabase “userdb” -u “user-01” -p command to launch MongoDB CLI (Client) by providing username and password.
- Step 6 — Similarly, below command can be used to execute mongo import for uploading bulk documents
mongoimport persons.json — port 27017 — authenticationDatabase “userdb” — username “user-01” — password ***** -d userdb -c contacts –jsonArray