12 January, 2020

MongoDB

liton

585 views


 

Create the user administrator.

From the mongo shell, add a user with the userAdminAnyDatabase role in the admin database. Include additional roles as needed for this user. For example, the following creates the user myUserAdmin in the admin database with the userAdminAnyDatabase role and the readWriteAnyDatabase role.

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

 

Create additional users as needed for your deployment.

Once authenticated as the user administrator, use db.createUser() to create additional users. You can assign any built-in roles or user-defined roles to the users.

The following operation adds a user myTester to the test database who has readWrite role in the test database as well as read role in the reporting database.

use test
db.createUser(
  {
    user: "myTester",
    pwd:  passwordPrompt(),   // or cleartext password
    roles: [ { role: "readWrite", db: "test" },
             { role: "read", db: "reporting" } ]
  }
)

 

Then disconnect from the mongo shell (Ctrl+D).

 

Bind IP & Enable authentication

 

Changed the bind_ip in /etc/mongod.conf file from

bind_ip = 127.0.0.1

to

bind_ip = 127.0.0.1,198.51.100.1

Enable authentication

 

Open /etc/mongod.conf with your favorite code editor and search for the following lines:

security:
    authorization: "disabled"

Change "disable" for "enabled", save the file and restart mongod :

Issue the following command to restart

sudo service mongod restart

Allow Port 27017 on firewall

sudo ufw allow 27017

 Now you can access through  198.51.100.1:27017  remotely,  if you visit through web browser it will show like:

It looks like you are trying to access MongoDB over HTTP on the native driver port.

Connect and authenticate as the user administrator.

Using the mongo shell, you can:

  • Connect with authentication by passing in user credentials, or
  • Connect first without authentication, and then issue the db.auth() method to authenticate.

Authenticate during Connection

Start a mongo shell with the -u -p, and the --authenticationDatabase command line options:

mongo --port 27017  --authenticationDatabase "admin" -u "myUserAdmin" -p

Enter your password when prompted.

Authenticate after Connection

mongo --port 27017

In the mongo shell, switch to the authentication database (in this case, admin), and use db.auth(, ) method to authenticate:

use admin
db.auth("myUserAdmin", passwordPrompt()) // or cleartext password

Enter the password when prompted.