MongoDB

MongoDB Authentication

 

This chapter describes how to create user with password in MongoDB 2.6.10 and above.

 

Start / stop Mongo server

1. without authentication: # mongod --noauth --config /etc/mongod.conf

2. with authentication: # mongod --auth --config /etc/mongod.conf

 --auth and --noauth can be defined inside /etc/mongod.conf

# mongod.conf

#where to log
logpath=/var/log/mongodb/mongod.log
logappend=true

# fork and run in background
fork=true

#port=27017

dbpath=/var/lib/mongodb

# location of pidfile
pidfilepath=/run/mongod.pid

# Listen to local interface only. Comment out to listen on all interfaces.
bind_ip=0.0.0.0

# Disables write-ahead journaling
# nojournal=true

# Enables periodic logging of CPU utilization and I/O wait
#cpu=true

# Turn on/off security.  Off is currently the default
#noauth=true
#auth=true

# Verbose logging output.
#verbose=true

# Inspect all client data for validity on receipt (useful for
# developing drivers)
#objcheck=true

# Enable db quota management
#quota=true

# Set oplogging level where n is
#   0=off (default)
#   1=W
#   2=R
#   3=both
#   7=W+some reads
#diaglog=0

# Ignore query hints
#nohints=true

# Enable the HTTP interface (Defaults to port 28017).
#httpinterface=true

# Turns off server-side scripting.  This will result in greatly limited
# functionality
#noscripting=true

# Turns off table scans.  Any query that would do a table scan fails.
#notablescan=true

# Disable data file preallocation.
#noprealloc=true

# Specify .ns file size for new databases.
# nssize=<size>

# Replication Options

# in replicated mongo databases, specify the replica set name here
#replSet=setname
# maximum size in megabytes for replication operation log
#oplogSize=1024
# path to a key file storing authentication info for connections
# between replica set members
#keyFile=/path/to/keyfile

 

3. stop server: # mongod --shutdown --config /etc/mongod.conf

 

 

Create root user

To create root user that will affect all databses use the following commands:

1. Start server without auth

# mongod --noauth --config /etc/mongod.conf

2. Enter mono shell client

# mongo

> use admin

> db.createUser({user: 'superadmin', pwd: 'myPass', roles: ['root']})

Notice: root role include all privilegies of readWriteAnyDatabase, dbAdminAnyDatabase, userAdminAnyDatabase and clusterAdmin. Sometimes ifwe want less privilegies just use readWriteAnyDatabase instead of root.

 

Now we can check is it possible to list databases in auth mode.

>exit

Restart the server in auth mode:

# mongod --shutdown --config /etc/mongod.conf

# mongod --auth --config /etc/mongod.conf

> use admin

> show collections

"$err" : "not authorized for query on admin.system.namespaces"

Error appear, so we have to login.

>db.auth("superadmin", "myPass")

> show collections    --- WORKS!!!

> use crawler

> show collections   --- ALSO WORKS due to 'root' or 'readWriteAnyDatabase' role

> db.content.find()  --- WILL WORK

 

 

Create user for specific database

A) when mongod is started with --noauth :

> use crawler

> db.createUser({user: 'crawler_user', pwd: 'crawlerPass', roles: ['dbOwner']})       --uses dbOwner role

 

B) when mongod is started with --auth :

> use admin

> db.auth("superadmin", "myPass")

> use crawler

> db.createUser({user: 'crawler_user', pwd: 'crawlerPass', roles: ['dbOwner']})

 

 

NodeJS natural API

Now in NodeJS we can use authenticated connection:

 

var dbName = 'mongodb://crawler_user:crawlerPass@localhost:27017/crawler';

 MongoClient.connect(dbName, function (err, db) {
    if (err) { logg.byWinston('error', __filename + ':20 ' + err); }

    db.collection(dbColl).find({}).sort({_id: -1}).limit(lim).toArray(function (err, mo_searchTerms) {
      if (err) { logg.byWinston('error', __filename + ':23 ' + err); }

      cb_index(res, mo_searchTerms);
    });


  });