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 mongod
Connect to mongodb using shell
$ mongosh
Use admin database
$ use admin
Create 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
$ exit
Modify the configuration file to enable authentication
$ sudo nano /etc/mongod.conf
Uncomment security option and add authentication. The previous content will be
#secutiry
There are 2 spaces before the
authorization: enabled
line. Save usingCtrl+X
, confirm usingY
andEnter
. After updating configuration it will look like this.
security:
authorization: enabledRestart mongod
$ sudo systemctl restart mongod
Verify the deamon is running and status is active
$ sudo systemctl status mongod
Connect 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)