How to setup user authentication in MongoDB 4.0

Standard

Creating the users

Let’s start, for real, by creating the actual users. Open your mongo shell and switch to the admin database:

use admin

Create the “admin” user (you can call it whatever you want)

db.createUser({ user: "admin", pwd: "adminpassword", roles: [{ role: "userAdminAnyDatabase", db: "admin" }] })

Don’t panic with all these brackets. We’re passing an “user” object to the createUser function, which contains a “roles” array. In the array we have one “role” object, which defines what the user can do and on which database.

In this case we’re giving the user the userAdminAnyDatabase role. This means that the admin user will be able manage (create, update, delete) users on all the databases of the MongoDB instance.

Make sure you use a safe password for the admin user, preferably generated by a password manager.

You can check that the user has been correctly created with this command:

db.auth("admin", "adminpassword")

The command will log you in as admin. Now exit the shell:

exit

We are now going to enable authentication on the MongoDB instance, by modifying the mongod.conf file. If you’re on Linux:

sudo nano /etc/mongod.conf

Add these lines at the bottom of the YAML config file:

security:
    authorization: enabled

This will enable authentication on your database instance. With nano, save with CTRL+X and confirm with y.

Now restart the mongod service (Ubuntu syntax).

sudo service mongod restart

You can check if the service is up with:

sudo service mongod status

Let’s go back in the mongo shell. Switch to the database admin and authenticate with the previously created user (called “admin”). Given that the user has the “userAdmin” role, it will be able to create and manage other users.

use admin
db.auth("admin", "adminpassword")

Now we will switch to an already created database and create a new user specifically for the database.

The following command will create an user with the role of dbOwner on the database. The dbOwner role will give to the user read and write permissions on all the collections of the database.

use yourdatabase
db.createUser({ user: "youruser", pwd: "yourpassword", roles: [{ role: "dbOwner", db: "yourdatabase" }] })

Check that everything went fine by trying to authenticate, with the db.auth(user, pwd) function.

db.auth("youruser", "yourpassword")
show collections

And that’s it, your MongoDB instance is now secured, provided that you used strong passwords.

When connecting with your favourite MongoDB Client from an application, use a connection string that will look like this:

mongodb://youruser:yourpassword@localhost/yourdatabase

Now, one last thing…

Protecting from external access

We’re now going to check that the MongoDB instance is listening on the local loopback interface only. This means that the DBMS will be accepting connections to the databases only when they come from the host itself.

You can of course adapt this to your needs, for example by enabling access on a private network interface, but the important thing to understand is that you should carefully decide which interfaces MongoDB should listen on. You should therefore avoid to expose the instance on the Internet if you don’t require to access it from the outside. And even if you do, there are much better ways to do that, for example by using an SSH tunnel. But that’s another story.

So, open mongod.conf in edit mode again, as we’re going to check out the net.bindIp option. That option tells the mongod process on which interfaces it should listen.

Examples of bindIp configuration

net:
    bindIp: 127.0.0.1

With this configuration, MongoDB will listen on 127.0.0.1 only (localhost). It means that you’ll be able to connect to your database only from the local machine.

NOTE: 127.0.0.1 is the default bind interface starting with MongoDB 3.6.0.

net:
    bindIp: 0.0.0.0

With this configuration, MongoDB will be listening on 0.0.0.0 (“all the networks”). It means that mongod will listen on all the interfaces configured on your system. Pay attention that in this way you are likely going to allow everyone on the Internet to access your database (as far as they have the credentials, of course, so pay particular attention to poor passwords).

You can also make MongoDB listen on more than one interface, by separing them with commas. This is useful if you want to make MongoDB listen on localhost and a private network interface.

net:
    bindIp: 127.0.0.1,172.21.200.200

A solution that you could consider is to set the bindIp option to 0.0.0.0 and then configure a firewall to filter incoming TCP requests on the MongoDB port and allow them only on specific interfaces.

install mongoDB on Linux

Standard

1) Create a /etc/yum.repos.d/mongodb-org-4.0.repo file so that you can install MongoDB directly using yum:

go to directory: /etc/yum.repos.d/
Create file: vi mongodb-org-4.0.repo
Paste data:
[mongodb-org-4.0]
name=MongoDB Repository
baseurl=https://repo.mongodb.org/yum/redhat/$releasever/mongodb-org/4.0/x86_64/
gpgcheck=1
enabled=1
gpgkey=https://www.mongodb.org/static/pgp/server-4.0.asc

2) Install the MongoDB packages.
sudo yum install -y mongodb-org

3) Start MongoDB.
sudo service mongod start

4) Begin using MongoDB.
mongo –host 127.0.0.1:27017

Shell script to import JSON files in mongodb

Standard
  • Following script will find all files in directory path mentioned below in “DIR” variable.
  • Read each file name in loop & execute mongodb import command i.e
    • mongoimport -d DATABASE_NAME -c TABLE_NAME –file FILE_PATH\FILE_NAME.json

#!/bin/sh

DIR=”NsBackupFiles/”
for eachFile in “$DIR”*
do
fileName=`echo $eachFile | cut -d’/’ -f 2`
tableName=`echo $fileName | cut -d’_’ -f 1`
echo $tableName
mongoimport -d ns_backup -c $tableName –file $eachFile
done