Skip to content

Instantly share code, notes, and snippets.

@volkancakil
Forked from tgrall/sec_tutorial.md
Created January 23, 2017 09:53
Show Gist options
  • Save volkancakil/2554e9f5d4fa22989dbea632871e3585 to your computer and use it in GitHub Desktop.
Save volkancakil/2554e9f5d4fa22989dbea632871e3585 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   } );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment