MongoDB Authentication | Authentication Commands in MongoDB

Authentication mechanism categories.

MongoDB authentication mechanisms can be grouped into the following two categories:

Authorization in mongodb (role-based access control)

In MongoDB, you control who has access to what resources on a database and to which degree through a mechanism called Role-Based Access Control, often shortened as RBAC.

Built-in roles

MongoDB comes with built-in roles that will help define restrictions across the database. The picture below shows available roles:

List of MongoDB built-in roles

You can restrict using these roles, for example:


  • Copydbgetnonce is a client library in MongoDB which was used in MongoDB to copy database one instance to other instance.
  • Copydbgetnonce is an essential and useful command in MongoDB to copy databases from one instance to another instance.
  • We have used copied command to copy one database to another database.
  • Below is the syntax of the Copydbgetnonce command.

How mongodb controls access with role-based access control

Access control — also known as authorization — is a security technique that involves determining who can gain access to which resources.


{logout: 1}

Mongodb enable authentication (enable access control)

Hi Folks,

In the context of databases, authentication acquires one more dimension because it may happen at different levels. It may be performed by the database itself, or the setup may be changed to allow either the operating system, or some other external method, to authenticate users.

Usually most of the databases like MySQL, MS SQL, Postgres, etc. comes with basic level of authentication. But in case of MongoDB the same cannot be said. MongoDB comes without any default authentication mechanisms. This provides restriction free access to all the users who can access any database or any data within it. This in trun raises security concerns.

Похожее:  Передать показания Показания за воду и - показания воды Калининград

There is a way provided to set up username and passwod for accessing the MongoDB in the official documentation. But the details provided are not clear enough to re-produce the same.

In this blog, we are going to see an elaborate step wise description on how to enable authentication for the accessing the MongoDB. The details specified below are for MongoDB 3.X version.


To follow along with this guide, you’ll need an account on a MongoDB server with the appropriate privileges.

Required privileges

To execute the commands above, you need to login to MongoDB with an account with a number of different privilege actions. The specific privileges you require depend on the commands you need to use.

Step 1 — outlining the example scenario and preparing the sample databases

To explain how Role-Based Access Control — RBAC, for short — works in practice, this guide follows an example scenario with an imaginary sales company called Sammy Sales that uses two databases.

The first database (called sales) will store data about customer orders in the company shop with two separate collections: customers for their customers’ personal data and orders for order details.

The second database (this one called reports) will store aggregated reports on monthly sales. This database will contain a single collection named reports.

The localhost exception

Perform a test to see how the various types of MongoDB supported authentication mechanisms work via Mongo shell and the Mongo server by starting MongoDB with the following command:

The server will display something like the following:NOTE: Some of the texts was removed from the below results. Notice the result says 2022-06-26T19:29:05.674 0800 I NETWORK [initandlisten] waiting for connections on port 27017

Похожее:  Как перевести деньги со своего счета другому абоненту, перекинуть деньги с Билайн Самара

Включение авторизации на mongodb

Прежде чем создать пользователя в mongodb, лучше включить авторизацию, для этого необходимо либо прописать в конфиге

security: authorization: enabled

Полный конфиг у нас будет выглядеть так

storage: dbPath: "/path/to/mongodata" systemLog: path: "/path/to/logs/mongod.log" logAppend: true destination: "file" net: bindIp : localhost processManagement: fork : true security: authorization: enabled

Либо запускать mongod с параметром —auth

mongod --auth

Если у вас не добавлено ни одного пользователя в mongodb, то после этого, вы сможете подключиться без авторизации только с localhost, для создания первого юзера. После создания первого юзера, вы не сможете подключится к серверу без авторизации даже с localhost. Это правильно называется Localhost Exception

Добавление юзера в mongodb без включенной авторизации

Если у вас еще не включена авторизация в конфиге, то вам достаточно присоединиться к mongodb


Создание пользователя mongodb с включенной авторизацией

Для того, чтобы создать пользователя с включенной авторизацией, но без единого пользователя в бд, убедитесь что у вас в конфиге установлено

net: bindIp : locahost

Далее подключитесь к mongodb


Recommended articles

This is a guide to MongoDB Authentication. Here we discuss an introduction to MongoDB Authentication, steps to enable Authentication and commands. You can also go through our other related articles to learn more –

  1. MongoDB Alternatives
  2. MongoDB Commands
  3. Is MongoDB Open Source
  4. MongoDB Collection
1 Звезда2 Звезды3 Звезды4 Звезды5 Звезд (1 оценок, среднее: 5,00 из 5)

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *