#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" }
]
}
)
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
use reporting
db.demo.find()
Test with all other databases, try to insert document you will see that it is not possible
$ 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 } );