Tutorials

Enable MongoDB Authentication

Table of Contents

Introduction

MongoDB is not configured with any user credentials by default. Best security practices recommend that an administrative user and database user be utilized in a production environment.

Requirements

  • MongoDB 2.6

Create Administrative User

An administrative user is added to the MongoDB "admin" database. Use the mongo client to connect to MongoDB.

mongo

Connect to the "admin" database and create the administrative user.

use admin
db.createUser(
      {
          user: "username",
          pwd: "password",
          roles: [ "root" ]
      }
  )

The new administrative user can now be used to log into a MongoDB database.

mongo -u username -p password --authenticationDatabase admin mydatabase

It is worth noting that the -p parameter without a following argument will prompt for the password. The authentication process will fail if the following argument is a database name as the command will interpret the argument as the password. The -p parameter must be followed by the password argument or another hyphenated parameter.

mongo -u username -p password admin

Create Database User

A database user is added to the specific database requiring authentication. The following commands will create a user in the database named "mydatabase" with read-write privileges.

use mydatabase
db.createUser(
    {
        user: "username",
        pwd: "password",
        roles: [
            { role: "readWrite", db: "mydatabase" }
        ]
    }
)

The database can then be accessed with the new user.

$ mongo -u username -p password --authenticationDatabase mydatabase

The --authenticationDatabase parameter is unnecessary if the database being accessed at the command line contains the user.

$ mongo -u username -p password --host localhost mydatabase

The --host parameter is used to prevent "mydatabase" from being interpreted as the password argument.

Further details on user and role management can be found in the online MongoDB manual.

 
  • Thanks for this impressive article if you were the user of windows 10 operating system and unable to find file explorer or any trouble there then from our tutorial you will learn that how to get help with file explorer in windows 10 operating system with the help of our tutorial which you will do it online.

  • It is the latest of our offerings which help to free organisations from the limited, inflexible choices provided by first generation cloud computing industry incumbents. We provide a better, ‘unbound’ cloud experience that delivers on the true promise of cloud computing. happy wheels 2 game

Log In, Add a Comment