DEV Community

Elson Jose
Elson Jose

Posted on

How to enable Authentication in mongodb ?

Lets learn how to enable authentication in a local installation of mongodb.

Note: These steps are to be done on a linux OS

  1. Start mongodb deamon
    $ sudo systemctl start mongod

  2. Connect to mongodb using shell
    $ mongosh

  3. Use admin database
    $ use admin

  4. Create new user. Replace USER_NAME & USER_PASSWORD with the values that you want.
    $ db.createUser(
    ... {
    ... user: "USER_NAME",
    ... pwd: "USER_PASSWORD",
    ... roles: ["readWriteAnyDatabase"]
    ... }
    ... )

  5. Exit shell
    $ exit

  6. Modify the configuration file to enable authentication
    $ sudo nano /etc/mongod.conf

  7. Uncomment security option and add authentication. The previous content will be
    #secutiry

  8. There are 2 spaces before the authorization: enabled line. Save using Ctrl+X, confirm using Y and Enter. After updating configuration it will look like this.
    security:
    authorization: enabled

  9. Restart mongod
    $ sudo systemctl restart mongod

  10. Verify the deamon is running and status is active
    $ sudo systemctl status mongod

  11. 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)