Mongo: enabling user auth

From lxadm | Linux administration tips, tutorials, HOWTOs and articles
Jump to: navigation, search

By default, mongo runs with user auth disabled.

To enable it, do the following:

Create admin user[edit]

First, connect to admin database and create "admin" user (it can be named anything, does not necessarily need to be called "admin"):

use admin
db.createUser(
  {
    user: "admin",
    pwd: "some-admin-password",
    roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
  }
)


Enable user auth in mongod.conf and restart mongod[edit]

In /etc/mongod.conf, make sure the following is present and restart mongod:

security:
    authorization: enabled


Connect to mongo shell with auth enabled[edit]

mongo --port 27017 -u admin -p "some-admin-pass" --authenticationDatabase "admin"


Create a non-admin user for database access[edit]

This one will create "phpunituser" with "readWrite" access to "phpunitdb" database. Make sure "use phpunitdb" is present before db.createUser(...):

use phpunitdb
db.createUser(
  {
    user: "phpunituser",
    pwd: "some-user-pass",
    roles: [ { role: "readWrite", db: "phpunitdb" } ]
  }
)


Connect to mongo shell as non-admin user[edit]

mongo --host 10.1.2.3 --port 27017 -u phpunituser -p "some-user-pass" --authenticationDatabase phpunitdb phpunitdb