Skip to content

Instantly share code, notes, and snippets.

@skarlekar
Last active July 20, 2018 20:05
Show Gist options
  • Save skarlekar/cf99d6a7f32766323223299b3e70ba3e to your computer and use it in GitHub Desktop.
Save skarlekar/cf99d6a7f32766323223299b3e70ba3e to your computer and use it in GitHub Desktop.
Secure MongoDB

Secure MongoDB

Start MongoDB

docker run -d --name mongo -p 27017:27017 -v ~/mongo-data:/data/db mongo --auth

List containers and ensure mongodb is running:

docker ps

Connect to MongoDB admin DB:

docker exec -it mongo mongo admin

Create admin user for MongoDB server

Create an admin user for the MongoDB server (not for the database)

db.createUser({user:'admin', pwd: 'admin1234', roles:[{role:'userAdminAnyDatabase', db: 'admin'}]});

Now exit from MongoDB shell

exit

Connect to the MongoDB Server

docker exec -it mongo mongo -u admin -p 'admin1234' --authenticationDatabase admin

Create an admin for the new database:

Create a users database (this could be any database that you want to secure).

use users

Create an administrator for the newly created database

db.createUser({ user: 'usersadmin', pwd: 'usersadmin1234', roles: ["readWrite", "dbAdmin"] });

MongoDB URL

Now you can use the following URL for connecting to MongoDB:

mongodb://usersadmin:usersadmin1234@localhost:27017/users

Attach to the running secure MongoDB

Run Docker exec to attach

This will authenticate you into MongoDB

docker exec -it mongo mongo -u admin -p 'admin1234' --authenticationDatabase admin

Authenticate into the Users database as follows:

use users
db.auth('usersadmin', 'usersadmin1234')

Now you can do a find on collections in the users database as follows:

db.userlist.find({})

Add a new user to the userlist collection in the users database as follows:

db.userlist.insert({"username" : "jdoe", "email" : "jdoe@email.com", "firstname" : "Jack", "lastname" : "Doe", "org" : "Org1", "password" : "$2a$10$ByqT8PI7Bq2m4Z8yXU1pF.9IcjrozOzpsa4HHBaxMXE.3Dj1HEnI6", "adminUser" : true, "authorizedApps" : [ "User Manager" ] })

Running MongoDB without security

docker run -d --name mongo -p 27017:27017 -v ~/mongo-data:/data/db mongo
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment