Enable Authentication to MongoDB Database
Using MongoDB without enabling authentication and access control lets anybody view and alter your data. It’s okay to work with MongoDB without access control when you are a novice developer but when it comes to deploying your application to production, you must enable authentication and access control to your MongoDB database. Adding access control on a MongoDB setup enforces authentication and authorization, expecting users to recognize themselves. While accessing a MongoDB setup that has authentication and authorization enabled, users can just perform activities as controlled by their roles. Here are the steps to do it.
Start MongoDB
sudo service mongod start
Connect to Mongo instance
anand@anandFolio:~$ mongo MongoDB shell version v4.0.13 connecting to: mongodb://127.0.0.1:27017/?gssapiServiceName=mongodb Implicit session: session { "id" : UUID("af4a23a8-8c73-4047-8ffc-a173c7ff48a0") } MongoDB server version: 4.0.13 >
Connect administrator user
The following creates the user admin
in the admin
database with the userAdminAnyDatabase
role and the readWriteAnyDatabase
role.
> use admin switched to db admin > db.createUser( { user: "admin", pwd: "anand@123", roles: [ { role: "userAdminAnyDatabase", db: "admin" }, "readWriteAnyDatabase" ] } )
Restart Mongo instance and authenticate with administrator
> exit bye anand@anandFolio:~$ mongo MongoDB shell version v4.0.13 connecting to: mongodb://127.0.0.1:27017/?gssapiServiceName=mongodb Implicit session: session { "id" : UUID("af4a23a8-8c73-4047-8ffc-a173c7ff48a0") } MongoDB server version: 4.0.13 > use admin switched to db admin > db.auth("admin", "anand@123")
Create additional users
> use ngclient switched to db ngclient > db.createUser( { user: "ngclient", pwd: "ngc@123", roles: [ { role: "readWrite", db: "ngclient" }] } )
The above statements creates the user ngclient
in the ngclient
database with the readWrite role. This user can access the ngclient database only. This would restrict the data to this particular user.