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

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

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

Enable user auth in mongod.conf and restart mongod

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

    authorization: enabled

Connect to mongo shell with auth enabled

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

Create a non-admin user for database access

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

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

Connect to mongo shell as non-admin user

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