Enable Authentication in MongoDB

Enable Authentication in MongoDB:-

Most RDBMS like MySQL, Oracle, SQLServer comes with inbuilt authentication setup with simple authentication. MongoDB has a different feature, it doesn’t comes with inbuilt basic authentication setup.There is no restriction to the MongoDB database inbuilt, any user can access any database.In this blog post, we are going to see how we can setup user authentication to our mongo database server and schema level.

Our Requirement:-

  1. We are going to authenticate database connection with an Admin User.
  2. We are going to create a User which as Owner permission to the specific database in MongoDb

Step 1: Connect MongoDb Without Authentication :-

We don’t have any authentication set in our mongo server so we can login by typing following command

Our host is 127.0.0.1 in case we are in local machine and port by default is 27017 .Now lets enable authentication in mongodb .

Step 2: Create a User:-

Open your mongo shell and enter the command below to Switch to admin database

Now We need to create a user which has root access to the database . Provides access to the operations and all the  resources ofreadWriteAnyDatabase,dbAdminAnyDatabaseuserAdminAnyDatabase clusterAdminroles, restoreand rolesbackup combined.

This user has all access to do any operation on any other databases including admin database.

Step 3: Configuring Mongod authentication configuration:-

Open a file mongod.conf located under etc using any editor of your choice.

You will see something like this:-

mongod.conf

Locate #security and add the following line just below of that, save and exit from your editor . Your updated file should look like the image below.

mongod.conf

Step 4 : Restart MongoDB:

Step 5 : Connect to Mongo and Authenticate admin User:-

Let’s connect to mongo shell and execute following commands to test the user we have just created.

 

You will get some error saying:-

It says you are not authorized to view collections inside admin database hence you need to authenticate yourself. This shows that your database has enabled authentication in MongoDB.



Let’s authenticate with the user we created .

We must get the output of db.auth() as 1.Now you have successfully enable authentication in MongoDB.

Let’s Create a database and create a Separate User for the database and try to enable authentication in MongoDB for that database.

Step 6 :Create Database, User and Enable Authentication for Specific Database:-

We are going to create a user with a role as  DbOwner for the database named as testMongo.

Now you don’t need to log in as admin in every database.We can use database specific users to access database and use admin user to manage all databases.

 

Leave a Reply

Your email address will not be published. Required fields are marked *