Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What MongoDB user privileges do I need to add a user to a new/another mongo database?

I have enabled authentication in the MongoDB config file after adding one admin user with the following privileges: userAdmin and userAdminAnyDatabase.

Now I connect with this user to the db where this admin user is defined (otherwise I get exception: login failed).

After I have successfully connected I want to add the a new user to a new database. For that I am trying:

use another
db.addUser(...)

but I get an error:

Wed Dec 11 17:45:18.277 couldn't add user: not authorized for insert on app.system.users at src/mongo/shell/db.js:128

How can I create a new database and add a first user to it?


Detailed (all users have 1234 as password in this example)

$ mongo mono -u admin_all -p 1234
MongoDB shell version: 2.4.6
connecting to: mono
> db.system.users.find()
{ "_id" : ObjectId("52a9831de41eb640bb0f5f64"), "user" : "admin_all", "pwd" : "a6316ed4886c10663cce46bc216ea375", "roles" : [  "userAdmin",  "userAdminAnyDatabase" ] }
{ "_id" : ObjectId("52a98404ef1f9bc934b62e11"), "user" : "admin_one", "pwd" : "884f516cf308a4c6a75bbc5a0a00807b", "roles" : [  "userAdmin" ] }
{ "_id" : ObjectId("52a98415ef1f9bc934b62e12"), "user" : "admin_any", "pwd" : "1616611df9b47c58b607054d384cab99", "roles" : [  "userAdminAnyDatabase" ] }
> use another
switched to db another
> db.addUser({ user: "user", pwd: "1234", roles: ["read"] })
{
    "user" : "user",
    "pwd" : "461d4f349d8d4ec3d22a4c945010c330",
    "roles" : [
        "read"
    ],
    "_id" : ObjectId("52a985372fcdbfd033003a7e")
}
Thu Dec 12 10:43:19.091 couldn't add user: not authorized for insert on another.system.users at src/mongo/shell/db.js:128
like image 358
4 revs, 2 users 76% Avatar asked Dec 11 '13 16:12

4 revs, 2 users 76%


1 Answers

The mistake made was that I was using an userAdminAnyDatabase user that was NOT in the admin database (see this note). So there MUST be a database called admin on your server! As the documentation says for the "AnyDatabase" privileges:

If you add any of these roles to a user privilege document outside of the admin database, the privilege will have no effect.

So you must:

  • add a userAdminAnyDatabase to the admin db

    $ mongo admin
    > db.createUser({ user: "myadmin", pwd: "1234", roles: ["userAdminAnyDatabase"] })
    
  • turn on authentication

    auth = true
    setParameter = enableLocalhostAuthBypass=0
    
  • connect using the new myadmin user to any database you want and add further users:

    $ mongo another -u myadmin -p 1234
    > db.createUser({ user: "user", pwd: "1234", roles: ["readWrite"] })
    

    or

    > use another
    > db.createUser({ user: "user", pwd: "1234", roles: ["readWrite"] })
    
like image 66
4 revs, 2 users 76% Avatar answered Sep 20 '22 00:09

4 revs, 2 users 76%