问题
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
回答1:
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 theadmin
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"] })
回答2:
This is what worked for me for creating a user prod
who connects to database prod
assuming I had an admin user (called admin
) already in the MongoDB:
> mongo admin --username root --password <pwd>
> use prod
> db.createUser(
{
user: "prod",
pwd: "<pwd>",
roles: [ { role: "dbOwner", db: "prod" } ]
}
)
> exit
After this you can login with the new user prod
like this:
> mongo prod --username prod --password <pwd>
来源:https://stackoverflow.com/questions/20525103/what-mongodb-user-privileges-do-i-need-to-add-a-user-to-a-new-another-mongo-data