Home > Net >  How to setup MongoDB with username and password
How to setup MongoDB with username and password

Time:03-14

I am setting up mongo db in ubuntu 18.04. I have installed it using the commands given on their 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 2nd 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 the 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.

Thanks

CodePudding user response:

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 " } ]
} )
  • Related