I have enabled authentication in the MongoDB config file after adding one admin user with the following privileges: userAdmin
and userAdminAnyDatabase
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>
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"] })