Search code examples
mongodbsecuritynosql

How to setup MongoDB with username and password


I am setting up MongoDB in Ubuntu 18.04. I have installed it using the commands given on their page. After the installation, I have downloaded NoSqlBooster and have connected to Mongo server using localhost.

I have created a database named RIPE and have also added some collections and test documents. At this point, I have also created some read users for RIPE so that I can share read user credentials with my colleagues for them to use it. I do not want them to make changes so just want to give them read access. Below is the screenshot:

enter image description here

My first question is, I have added ttread user in RIPE db which we can see in above image but why its showing it outside of RIPE db as well?

My second question is, how can I make users to directly connect to RIPE db. In nosqlbooster, when I am connecting to localhost, I have mentioned AuthDB as RIPE as shown below:

enter image description here

enter image description here

and when it connects it shows other db as well like, admin, config, local.

Last question, while setting up MongoDB how can I add a username and password because any user can connect to localhost without username and password. So what is the best way to setup security?


Solution

  • In order to enable authentication do following steps:

    1. Change your configuration file and enable authentication:

      security:
        authorization: enabled
      
    2. Restart your MongoDB, typically systemctl restart mongod

    3. Create the user administrator

      db.getSiblingDB("admin").createUser({
         user: "root",
         pwd: passwordPrompt(), // or cleartext password
         roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
      })
      

    Unless the user administrator is created you can still connect to your MongoDB without username/password, this behavior is called Localhost Exception

    Personally I don't see any reason to create users in other database than admin, see What is the "admin" database in mongodb?.

    I would create the user like this:

    db.getSiblingDB("admin").runCommand( {
       createUser: "ttread",
       pwd: passwordPrompt(),
       roles: [ { role: "read", db: "RIPE " } ]
    } )