Skip to content

Instantly share code, notes, and snippets.

@tgrall
Last active September 4, 2020 07:27
Show Gist options
  • Star 16 You must be signed in to star a gist
  • Fork 11 You must be signed in to fork a gist
  • Save tgrall/75c30ee302384c28d3cc to your computer and use it in GitHub Desktop.
Save tgrall/75c30ee302384c28d3cc to your computer and use it in GitHub Desktop.
MongoDB Security Tutorial

#Simple MongoDB Security Tutorial

###1 - Start mongod without any "security option"

$ mongod --port 27017

###2 Connect to it with mongoshell and create a new user

$ mongo

use admin

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

###3 Restart your mongod instance with the auth parameter

$ mongod --port 27017 --auth

Now your DB server will check authentication before doing anything

For example try the following

$ mongo

use demo

db.coll.insert( { x:"test" } );

You should see an error since you are not authenticated

###4 Connect to the DB using admin user

$ mongo -u admin -p password --authenticationDatabase admin

You are now connected with an admin user that has all the permissions, (userAdminAnyDatabase), so you can create new users, and database

####Create a new user, on a specific db (reporting)

use reporting

db.createUser(
    {
      user: "reportsUser",
      pwd: "password",
      roles: [
         { role: "read", db: "reporting" },
         { role: "read", db: "products" },
         { role: "read", db: "sales" }
      ]
    }
)

Create database and content

You are still connected as admin user

use reporting

db.demo.insert({ name : "This is the reporting db"  });


use products

db.demo.insert({ name : "This is the products db"  });


use sales

db.demo.insert({ name : "This is the sales db"  });

###5 Connect with reporting user

Now we will connect with the reporting user

$ mongo -u reportsUser -p password --authenticationDatabase reporting

note that we are telling on which db we want to validate the user

Do some queries

use reporting

db.demo.find()

Test with all other databases, try to insert document you will see that it is not possible

Change user roles/permissions

$ mongo -u admin -p password --authenticationDatabase admin

use reporting

db.grantRolesToUser(
    "reportsUser",
    [
      { role: "readWrite", db: "products" }
    ]
)

####Reconnect with reportsUser and create document in products db

$ mongo -u reportsUser -p password --authenticationDatabase reporting

use products


db.demo.insert( { x : 0   } );
@viperumal
Copy link

viperumal commented Apr 4, 2020

Excellent Demonstration.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment