Search code examples
mongodbshellauthenticationadmindatabase

MongoDB: Understand createUser and db admin


My MongoDB is hosted on compose.io and is called ScroungeBA. I try to create a user with some built-in roles which by the documentary only work in the admin database:

MongoDB provides all other built-in roles only on the admin database

So my question: What is that admin db about? Is it the standard db which always exists?

Furthermore I have trouble with (using MongoDB shell version: 3.0.5):

$ use admin
switched to db admin
$ db.auth("user", "secret")
Error: 18 Authentication failed.

I guess my user does exist in the ScroungeBA db but not in the admin db? How can I create a user in the admin db since

db.createUser({user:"hello", pwd:"world", roles:[{role: "userAdmin", db: "admin"}]})

results in the error:

Error: couldn't add user: not authorized on admin to execute command { createUser: "hello", pwd: "xxx", roles: [ { role: "userAdmin", db: "admin" } ], digestPassword: false, writeConcern: { w: "majority", wtimeout: 30000.0 } }
at Error (<anonymous>)
at DB.createUser (src/mongo/shell/db.js:1101:11)
at (shell):1:4 at src/mongo/shell/db.js:1101

Solution

  • The admin database is a special database that you automatically have with a MongoDB instance. It contains things like the users of your databases, with roles, custom data, etc.

    To create a user in the admin database, you have to temporarily disable auth on your MongoDB instance. I don't know how compose.io works specifically, but I usually modify the mongod.conf file, and comment the line auth=true.

    After that, you can connect to your MongoDB shell and create a user in the admin database.

    Give the user the role userAdminAnyDatabase instead of just useAdmin.

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

    An user with the role userAdminAnyDatabase can manage the users of all the databases.

    Now enable auth again and restart the service.

    As I said, I'm not sure how compose.io actually works and how much control it gives to you. If you don't have an admin account, this should be the way to go.

    By the way, I've published an article on Medium about MongoDB 3.0 auth.