mongodb authentication setting

The steps below to create authentication for mongodb assumes the mongodb was installed on mac os with homebrew, but shouldn’t be much of a difference other than the file locations.

Create a mongodb key file

cd ~
mkdir .keyfile
cd .keyfile
openssl rand -base64 741 > mongodb_keyfile
chmod 600 mongodb_keyfile

Create a mongodb config file /usr/local/etc/mongod.conf and put these configurations. Change yourusername to yours.

security:
    keyFile: /Users/yourusername/.keyfile/mongodb_keyfile
systemLog:
  destination: file
  path: /usr/local/var/log/mongodb/mongo.log
  logAppend: true
storage:
  dbPath: /usr/local/var/mongodb
net:
  bindIp: 127.0.0.1

Start mongodb with this command line and then shell into mongodb

mongod --config /usr/local/etc/mongod.conf &
mongo

Create amdin user in mongodb shell and exit.

use admin
db.createUser(
  {
    user: "admin",
    pwd: "password",
    roles: [ { role: "root", db: "admin" } ]
  }
);
exit;

Shell back into mongodb with the above admin user

mongo --port 27017 -u admin -p password --authenticationDatabase admin

Create user for a database called test, with read access to database test1, test2, test3, read and write access to test4

use test
db.createUser(
    {
      user: "tester",
      pwd: "password",
      roles: [
         { role: "read", db: "test1" },
         { role: "read", db: "test2" },
         { role: "read", db: "test3" },
         { role: "readWrite", db: "test" }
      ]
    }
);

Shell into mongodb with the test user

mongo -u tester -p --authenticationDatabase test

Search within Codexpedia

Custom Search

Search the entire web

Custom Search