Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save anandkkpr/597877a5210935aac4a4e6a137300206 to your computer and use it in GitHub Desktop.
Save anandkkpr/597877a5210935aac4a4e6a137300206 to your computer and use it in GitHub Desktop.
MongoDB admin and database user and role creation

Get MongoDB

https://www.mongodb.org/downloads

Or the apt repo based tutorial here for Ubuntu: http://docs.mongodb.org/manual/tutorial/install-mongodb-on-ubuntu/

MongoDB should match the python pymongo where possible to avoid version mismatch problems.

Take note about updating the mongod.conf file to a non-local host IP if doing db replication.

Start the shell

mongo

Sanity Check

db.version()

The current version of Mongo's manual is here: http://docs.mongodb.org/manual/

Create the first MongoDB Admin user

The permissions model is based on roles. For production, be very certain to remove unneeded roles. Admin can take additional roles, including "root", "dbAdminAnyDatabase", and "clusterAdmin".

use admin;
db.createUser(
  {
    user: "admin",
    pwd: "password",
    roles: ["dbOwner", "userAdmin", "userAdminAnyDatabase"]
  }
);

Verify new Admin user was created.

db.system.users.find();

use yourDatabase;
db.createUser(
  {
    user: "username01",
    pwd: "aUsername01pwd",
    roles: [
       { role: "dbOwner", db: "yourDatabase" },
       { role: "dbAdmin", db: "yourDatabase" },
       { role: "readWrite", db: "yourDatabase" }
    ]
  }
);

use admin;
db.system.users.find();

Stop MongoDB

Make sure the correct mongodb server instance is started (check ps)

Linux: sudo service mongod stop

Enable authentication

MongoDB 3.4.2: sudo vi /etc/mongodb.conf

MongoDB 3.0.6: sudo vi /etc/mongod.conf

Add authentication to mongod.conf:

security:
  authorization: enabled

If you don't have that file, something is strange or not mongo v3.0. Check package installation.

Internal Authentication: https://docs.mongodb.org/manual/tutorial/enable-internal-authentication/

security:
  keyFile: /path/to/certificates/PSK.key

Start the server

Linux: sudo service mongod start

Test authentication

To connect: mongo yourDatabase -u <username> -p

The password will be prompted so it won't show in your shell command history.

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