Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Read only user in Mongo DB Instance for a particular database

I have created a user "mongo01testro" in the mongo01test database.

use mongo01test 
db.addUser( "mongo01testro", "pwd01", true );
db.system.users.find();
{ "_id" : ObjectId("53xyz"), "user" : "mongo01testro", "readOnly" : true, "pwd" : "b9eel61" }

When I logged in from another session as this newly created user, I am able to insert documents into the collection which is strange.

I am looking to do the following:

  1. Create 2 separate users one for read only and one for read write for each database.
  2. Create an admin user which have sysadmin/dba access to all the databases in MongoDB instance used for Backup/Recovery or admin purpose.

Please kindly help.

Regards, Parag

like image 209
user3111436 Avatar asked Jan 21 '14 11:01

user3111436


1 Answers

You forgot --auth to enable

Create Users

// ensure that we have new db, no roles, no users
use products
db.dropDatabase()

// create admin user
use products
db.createUser({
    "user": "prod-admin",
    "pwd": "prod-admin",
    "roles": [
        {"role": "clusterAdmin", "db": "admin" },
        {"role": "readAnyDatabase", "db": "admin" },
    "readWrite"
    ]},
    { "w": "majority" , "wtimeout": 5000 }
)

// login via admin acont in order to create readonly user
// mongo --username=prod-admin --password=prod-admin products
db.createUser({
    "user": "prod-r",
    "pwd": "prod-r",
    "roles": ["read"]
})

Enable auth:

sudo vim /etc/mongod.conf # edit file
    # Turn on/off security.  Off is currently the default
    #noauth = true
    auth = true
sudo service mongod restart # reload configuiration

Check write restriction:

# check if write operation for readonly user
$ mongo --username=prod-r --password=prod-r products
MongoDB shell version: 2.6.4
connecting to: products
> db.laptop.insert({"name": "HP"})
WriteResult({
    "writeError" : {
        "code" : 13,
        "errmsg" : "not authorized on products to execute command { insert: \"laptop\", documents: [ { _id: ObjectId('53ecb7115f0bfc61d8b1113e'), name: \"HP\" } ], ordered: true }"
    }
})

# check write operation for admin user
$ mongo --username=prod-admin --password=prod-admin products
MongoDB shell version: 2.6.4
connecting to: products
> db.laptop.insert({"name": "HP"})
WriteResult({ "nInserted" : 1 })

# check read operation for readonly user    
$ mongo --username=prod-r --password=prod-r products
MongoDB shell version: 2.6.4
connecting to: products
> db.laptop.findOne()
{ "_id" : ObjectId("53ecb54798da304f99625d05"), "name" : "HP" }
like image 186
Andrei.Danciuc Avatar answered Sep 24 '22 19:09

Andrei.Danciuc