How to Enable Authentication and Create DB Users in MongoDB

By default authentication is not enabled within Mongo.  In this article we will show you how to enable authentication , create an account for global mongo administration and also create an account for database level authentication.

Create UserAdmin

First of all we go into the mongo shell and create our admin user.

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

Enable Auth

Next we enable authentication via the use of the –auth  switch.

mongo --auth --config /etc/mongo.conf

You can use the following command to check to see that auth is enabled db.getUsers()

> db.getUsers()
2016-10-24T12:35:16.962+0100 Error: not authorized on test to execute command { usersInfo: 1.0 
} at src/mongo/shell/db.js:1363

Create DB Users

Finally lets create another user and assign it to a single database.

db.auth('admin','password')
use example
db.createUser(
  {
    user: "example",
    pwd: "password",
    roles: [ { role: "readWrite", db: "example" } ]
  }
)

Django

In order to connect to Mongo with your new user you must first install pymongo,

pip install pymongo==2.8.1

Next add the following is added to your settings.py

import mongoengine

_MONGODB_USER = 'example'
_MONGODB_PASSWD = 'password'
_MONGODB_HOST = '127.0.0.1'
_MONGODB_NAME = 'example'

mongoengine.connect(_MONGODB_NAME, host='mongodb://%s:%s@%s:27017/%s' % (_MONGODB_USER,
                                                                         _MONGODB_PASSWD,
                                                                         _MONGODB_HOST,
                                                                         _MONGODB_NAME))
Rick Donato

Want to become a database expert?

Here is our hand-picked selection of the best courses you can find online:
Ultimate MySQL Bootcamp
Complete SQL Bootcamp
MongoDB Complete Developer course
and our recommended certification practice exams:
AlphaPrep Practice Tests - Free Trial