Lets learn how to enable authentication in a local installation of mongodb.
Note: These steps are to be done on a linux OS
Start mongodb deamon
$ sudo systemctl start mongodConnect to mongodb using shell
$ mongoshUse admin database
$ use adminCreate new user. Replace USER_NAME & USER_PASSWORD with the values that you want.
$ db.createUser(
... {
... user: "USER_NAME",
... pwd: "USER_PASSWORD",
... roles: ["readWriteAnyDatabase"]
... }
... )Exit shell
$ exitModify the configuration file to enable authentication
$ sudo nano /etc/mongod.confUncomment security option and add authentication. The previous content will be
#secutiryThere are 2 spaces before the
authorization: enabledline. Save usingCtrl+X, confirm usingYandEnter. After updating configuration it will look like this.
security:
authorization: enabledRestart mongod
$ sudo systemctl restart mongodVerify the deamon is running and status is active
$ sudo systemctl status mongodConnect to mongoDb using shell.
$ mongosh -u "USER_NAME" -p "USER_PASSWORD" --authenticationDatabase "admin"
If everything is correct it will connect to the default test database. To verify whether authentication is working use $ exit command and try to connect to mongoDb using
$ mongosh and list databases $ show dbs. It will return an error saying "MongoServerError: command listDatabases requires authentication".
Top comments (0)