Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 929
Senju Avatar asked Aug 07 '15 09:08

Senju


2 Answers

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.

like image 51
mcont Avatar answered Oct 15 '22 12:10

mcont


This solved my problem:

I finally got it to work on compose.io! So here it what my oplog url ended up looking like: "MONGO_OPLOG_URL": "mongodb://username:[email protected]:1111/local?authSource=myDB"
I keep the MONGO_URL exactly the same as the URL compose.io provides with ?replicaSet
But for the OPLOG_URL you can only use a single host, not multiple. So you have to edit the URL compose.io gives you to only have one host. And you can't end the oplog with ?replicaSet. you can only have the ?replicaSet in the MONGO_URL.

source

like image 21
Senju Avatar answered Oct 15 '22 12:10

Senju