MongoDB 3.2 - creating a CRUD admin for a certain database - mongodb

I'm trying to create a CRUD database administrator.
From what I read from official documentation, there is a role readWrite, but I don't really got the process of creating an admin.
So I ran mongod without --auth and created a user with these parameters:
use myCustomDB
db.createUser({
user: "snoop",
pwd:"stickyickyicky",
roles:[{role:"readWrite", db:"myCustomDB"}]
});
The command line answered Successfully added new user blah blah..
but when I authenticate it returns 1, which, I suppose is true. But when I run command for example db.peops.find() it gives me this Error: error: { "$err" : "not authorized for query on myCustomDB.peops", "co de" : 13 }

It may be your find call. Try formatting like this:
db.getCollection('peops').find({})
If that's not it, it might be your auth schema. This may not be the best method, but I thought I would share the steps I take to setup a super admin and database specific admin, and a read only user. The all caps should be replaced with corresponding credential / db name:
1.Change Mongo Security Method
sudo service mongod start
mongo
use admin
db.system.version.remove({})
db.system.version.insert({ "_id" : "authSchema", "currentVersion" : 3 })
2.Create Super Admin User
use admin
db.createUser( { user: "SUPERADMINUSER", pwd: "SUPERADMINPASS", roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] } )
3.Create db Admin with read/write access
use DATABASE
db.createUser( { user: "DBADMIN", pwd: "DBPASSWORD", roles: [ { role: "userAdmin", db: "DATABASE" }, { role: "readWrite", db: "DATABASE" }] } )
db.createUser( { user: "DBREADONLYUSER", pwd: "DBREADONLYPASS", roles: [ { role: "read", db: "DATABASE" }] } )
4.Edit mongod.config in /etc folder
sudo service mongod stop
in mongod.config edit so that auth = true is not commented out.
5. Restart mongo, security in place
sudo service mongod start
***Troubleshooting: If you are running mongo 3.2 you can likely skip the db.system.version remove and insert commands, you may want/need to upgrade to SCRAM-SHA-1, if so run db.adminCommand({authSchemaUpgrade: 1}); set up users the same way as shown above, when editing your /etc/mongod.conf file instead of auth=true comment in security: and add authorization=true as follows:
security:
authorization: enabled

Related

Create Dockerfile for mongoDB 4.2 with authentication

how would you script the Dockerfile to create admin user for mongoDB 4.2 ?
Is there a one line command to create admin users not using an interactive subshell ? (didn't see any in mongoDB documentation)
Thanks for your help.
Passing MONGO_INITDB_ROOT_USERNAME and MONGO_INITDB_ROOT_PASSWORD does not work anymore (removed from Docker hub mongo image documentation).
The mongo Docker hub documentation only shows interactive shell admin user creation.
> mongo admin
executes mongo interactive shell but how do you write a shell script to enter commands in that subshell from the top level shell ?
FROM mongo
RUN mongo admin ???? db.createUser({ user: 'jsmith', pwd: 'some-initial-password', roles: [ { role: "userAdminAnyDatabase", db: "admin" } ] });
The docker build process should display:
Successfully added user: {
"user" : "jsmith",
"roles" : [
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
}
]
}
OK, here's the way to add authetication via the Dockerfile.
create a init.js file:
db = new Mongo().getDB("admin");
// create admin user
db.createUser({
user: "admin",
pwd: "password",
roles: [
{
role: "clusterAdmin",
db: "admin"
}
]
});
// create non admin user
db.createUser({
user: "toto",
pwd: "123",
roles: [
{
role: "readWrite",
db: "tube"
}
]
});
create the Dockerfile:
FROM mongo
# init.js will be executed when the mongo instance runs
COPY ./init.js ./docker-entrypoint-initdb.d
build your docker image
docker build -t mongoAuth .
run the container (attached mode to see the logs)
docker run --name mongoContainer -p 27017:27017 mongoAuth
What I was missing was that I didn't set the database on which to create the users (admin database) by using:
db = new Mongo().getDB("admin");

show dbs gives "Not Authorized to execute command" error

I've spent some time trying to figure out what is wrong but as I could not find out, I decided to ask here.
I am running MongoDB(Windows 64-bit 2008 R2+) version 3.2.3 on Windows 8, the paths are :
C:\MongoDB\bin for the installation
C:\data\db for the data folder
I've installed following this video and this tutorial from the official documentation.
The first issue might be, as I don't really know if it is an issue at all, the connection between the client(mongo.exe) and the server(mongod.exe).
I lauched mongod.exe via the command line (with administrator rights), everything went fine, I got the message :
waiting for connections on port 27017
but when I launch mongo.exe via a new instance of the command line, the server(mongod.exe) doesn't print a message saying there is a new connection (it was the case in the tutorials I watched)
On the other side, mongo.exe prints
connecting to : test
I don't know if everything is correct at this point but I still tried some basics commands like :
show dbs returns not authorized on admin to execute command
Basically, all the commands I tried had the same error message, even with "fresh" db I just created with use 'dbName'
Some answers online said I have to create a user with proper roles, I tried this one.
Still the same error message not authorized to execute command
My question is the following :
Is is normal that mongod.exe doesn't show a new connection when I launch mongo.exe ? If it is correct then what can I do to make even the basic commands work ?
Additional Informations :
I tried to uninstall/re-install few times, with the "Custom mode" and the "Complete mode" in the Windows installer but it always lead to the same problem.
I also tried to create a MongoDB Service following the official documentation but I'm not really sure if it was a good idea. (I can't add more links but it is in a section in the second link I shared.
Edit section :
I decided to try it on another computer which I have not touched for years, running on Windows 7 64-bit.
I copied the MongoDB installation folder at the root of this computer, created \data\db folder and launched mongod.exe.
Then I launched mongo.exe and this time, mongod.exe printed a message saying there is a new open connection which it doesn't on my actual computer. I think the problem is here because I was able to start the basic tutorial from the official documentation and perform simple commands like create a new db, insert, find, show dbs, etc. Everything that I am not able to do on my actual computer.
So I think the problem is coming from the connection between mongod.exe and mongo.exe
Do you have any idea how I could solve this problem as I have tried uninstalling few times.
You should have started the mongod instance with access control, i.e., the --auth command line option, such as:
$ mongod --auth
Let's start the mongo shell, and create an administrator in the admin database:
$ mongo
> use admin
> db.createUser(
{
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
Now if you run command "db.stats()", or "show users", you will get error "not authorized on admin to execute command..."
> db.stats()
{
"ok" : 0,
"errmsg" : "not authorized on admin to execute command { dbstats: 1.0, scale: undefined }",
"code" : 13,
"codeName" : "Unauthorized"
}
The reason is that you still have not granted role "read" or "readWrite" to user myUserAdmin. You can do it as below:
> db.auth("myUserAdmin", "abc123")
> db.grantRolesToUser("myUserAdmin", [ { role: "read", db: "admin" } ])
Now You can verify it (Command "show users" now works):
> show users
{
"_id" : "admin.myUserAdmin",
"user" : "myUserAdmin",
"db" : "admin",
"roles" : [
{
"role" : "read",
"db" : "admin"
},
{
"role" : "userAdminAnyDatabase",
"db" : "admin"
}
]
}
Now if you run "db.stats()", you'll also be OK:
> db.stats()
{
"db" : "admin",
"collections" : 2,
"views" : 0,
"objects" : 3,
"avgObjSize" : 151,
"dataSize" : 453,
"storageSize" : 65536,
"numExtents" : 0,
"indexes" : 3,
"indexSize" : 81920,
"ok" : 1
}
This user and role mechanism can be applied to any other databases in MongoDB as well, in addition to the admin database.
(MongoDB version 3.4.3)
one more, after you create user by following cmd-1, please assign read/write/root role to the user by cmd-2. then restart mongodb by cmd "mongod --auth".
The benefit of assign role to the user is you can do read/write operation by mongo shell or python/java and so on, otherwise you will meet "pymongo.errors.OperationFailure: not authorized" when you try to read/write your db.
cmd-1:
use admin
db.createUser({
user: "newUsername",
pwd: "password",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
})
cmd-2:
db.grantRolesToUser('newUsername',[{ role: "root", db: "admin" }])
Create a user like this:
db.createUser(
{
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
}
)
Then connect it following this:
mongo --port 27017 -u "myUserAdmin" -p "abc123" --authenticationDatabase "admin"
Check the manual :
https://docs.mongodb.org/manual/tutorial/enable-authentication/
Copy of answer OP posted in question:
Solution
After the update from the previous edit, I looked a bit about the connection between client and server and I found out that even when mongod.exe was not running, there was still something listening on port 27017 with netstat -a
So I tried to launch the server with a random port using
[dir]mongod.exe --port 2000
Then the shell with
[dir]mongo.exe --port 2000
And this time, the server printed a message saying there is a new connection.
I typed few commands and everything was working perfectly fine, I started the basic tutorial from the documentation to check if it was ok and for now it is.
There are two things,
1) You can run the mongodb instance without username and password first.
2) Then you can add the user to the system database of the mongodb which is default one using the query below.
db.createUser({
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
})
Thanks.
Try this...
use admin;
db.createUser({
user: 'admin',
pwd: 'SecurePass',
roles: [ { role: 'root', db: 'admin' } ]
});
db.auth("admin", "SecurePass");
db.grantRolesToUser('admin', [{ role: 'root', db: 'admin' }])
db.auth() before db.grantRolesToUser()
solve my problem :)
if it doesn't work try to change the role to 'readWrite'
It was Docker running in the background in my case. If you have Docker installed, you may wanna close it and try again.
for me it worked by adding
1) "You can run the mongodb instance without username and password first.---OK
2) "Then you can add the user to the system database of the mongodb which is default one using the query below".---OK
db.createUser({
user: "myUserAdmin",
pwd: "abc123",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ],
mechanisms:[ "SCRAM-SHA-1" ] // I added this line
})

Meteor and MongoDB: Authentication failures

If I run Meteor locally it works perfectly. If I call Meteor with a MONGO_URL that has no username:password it works perfectly too. However, if I turn on the MongoDB authentication and restart and then run Meteor with the username:password set, as in MONGO_URL="mongodb://username:password#127.0.0.1:27017/meteor", then I get an authentication failure as Meteor loads. I have checked that the username and password are correct. I have read that there maybe problems with Meteor and MongoDB authentication so does anyone have any information on this? I am using the following versions:
Meteor - 1.0.3.2
MongoDB - 2.6.7 (installed via brew)
I20150304-21:48:00.597(1)? Exception in callback of async function: MongoError: auth failed
I20150304-21:48:00.598(1)? at Object.toError (/Users/me/.meteor/packages/mongo/.1.0.11.1hg8e3j++os+web.browser+web.cordova/npm/node_modules/mongodb/lib/mongodb/utils.js:110:11)
I20150304-21:48:00.598(1)? at /Users/me/.meteor/packages/mongo/.1.0.11.1hg8e3j++os+web.browser+web.cordova/npm/node_modules/mongodb/lib/mongodb/db.js:1128:31
I20150304-21:48:00.598(1)? at /Users/me/.meteor/packages/mongo/.1.0.11.1hg8e3j++os+web.browser+web.cordova/npm/node_modules/mongodb/lib/mongodb/db.js:1843:9
I20150304-21:48:00.598(1)? at Server.Base._callHandler (/Users/me/.meteor/packages/mongo/.1.0.11.1hg8e3j++os+web.browser+web.cordova/npm/node_modules/mongodb/lib/mongodb/connection/base.js:445:41)
I20150304-21:48:00.598(1)? at /Users/me/.meteor/packages/mongo/.1.0.11.1hg8e3j++os+web.browser+web.cordova/npm/node_modules/mongodb/lib/mongodb/connection/server.js:468:18
I20150304-21:48:00.598(1)? at [object Object].MongoReply.parseBody (/Users/me/.meteor/packages/mongo/.1.0.11.1hg8e3j++os+web.browser+web.cordova/npm/node_modules/mongodb/lib/mongodb/responses/mongo_reply.js:68:5)
I20150304-21:48:00.599(1)? at [object Object].<anonymous> (/Users/me/.meteor/packages/mongo/.1.0.11.1hg8e3j++os+web.browser+web.cordova/npm/node_modules/mongodb/lib/mongodb/connection/server.js:426:20)
I20150304-21:48:00.599(1)? at [object Object].emit (events.js:95:17)
I20150304-21:48:00.599(1)? at [object Object].<anonymous> (/Users/me/.meteor/packages/mongo/.1.0.11.1hg8e3j++os+web.browser+web.cordova/npm/node_modules/mongodb/lib/mongodb/connection/connection_pool.js:201:13)
I20150304-21:48:00.599(1)? at [object Object].emit (events.js:98:17)
=================================================
I thought I had an answer to the above but alas not, I made suggested changes and I still could not authenticate. So, to provide more details:
I have upgraded to MonogoDB 3.0.0
I delete the database so that a brand new one was created.
My config file is as follows:
systemLog:
destination: file
path: /usr/local/var/log/mongodb/mongo.log
logAppend: true
storage:
dbPath: /usr/local/var/mongodb
net:
bindIp: 127.0.0.1
security:
authorization: enabled
On the "admin" database a "super user" has been created as follows:
use admin
db.createUser({user: "superuser", pwd: "password", roles:["root"]})use admin
I then created a user on the "meteor" database
db.auth("superuser", "password")
use meteor
db.createUser({user: "meteor", pwd: "password", roles: [{ role: "readWrite", db: "meteor"}]})
The above step generates:
Successfully added user: {
"user" : "meteor",
"roles" : [
{
"role" : "readWrite",
"db" : "meteor"
}
]
}
If I perform a db.getUsers() I get the message:
[
{
"_id" : "meteor.meteor",
"user" : "meteor",
"db" : "meteor",
"roles" : [
{
"role" : "readWrite",
"db" : "meteor"
}
]
}
]
If I comment out the two security lines in the config then I can access MongoDB from Meteor or RoboMongo without a problem - using mongodb:127.0.0.1:27017/meteor. If I uncomment the two security lines in the config then I can no longer access MongoDB from either Meteor or MongoDB - using mongodb://meteor:password#127.0.0.1:27017/meteor. In the last instance I continue to get the message that authentication failed. In the MongoDB logs I have:
authenticate db: meteor { authenticate: 1, nonce: "xxx", user: "meteor", key: "xxx" }
2015-03-08T14:34:44.909+0100 I ACCESS [conn7] Failed to authenticate meteor#meteor with mechanism MONGODB-CR: AuthenticationFailed UserNotFound Could not find user meteor#meteor
Update
The answer below and the configuration above work on v2.6.7
I haven't seen the issues you describe and without seeing code or knowing how you "turned on" MongoDB authentication I need to guess - so let's focus on what made things work for me.
You should check where the user was created. In MongoDB there are multiple databases, each having their own users. When using your connection string
mongodb://username:password#127.0.0.1:27017/meteor
you are authenticating against the meteor database. Using a tool such as RoboMongo I'd check if the user is actually inside that database or whether you created it inside the admin (or any other) database.
As a quick rundown:
When securing MongoDB you need to set an admin account, change the mongodb.conf file that it contains the line auth = true and restart. Then using the admin account you create a new (low-privilege) db user that has only access to the meteor database. You can do this using the command line like this (code for 2.6 as this was in your questions and will be default for next Meteor version):
db.createUser(
{ user: "username",
pwd: "password",
roles: [
{ role: "readwrite", db: "meteor" }
]
})
If you run mongod on the same box as Meteor I think we can safely rule out any issues with net.port or net.bindIpconfig settings where the DB would simply not listen to requests.
If you did all this and restarted MongoDB, perhaps a meteor reset inside your projects can help fix anything.
it turns out for me was just about having special chars on the password and a dash on the username, once i made it simpler it all worked like magic :(
I had the same issue when I deployed on my new VPS.
On this new VPS, mongo version is 3.0.1
To solve the problem, a meteor update before building the package and it works
(meteor version: 1.0.4.1)

couldn't add user: Could not lock auth data update lock

I am trying to setup authentication on a mongodb shard cluster(1 mongos, 3 mongod, 3 mongo configsvr). I have restarted all the components in the cluster with parameter --keyFile, then login via mongos to add administrator user in the admin database. But encountered this error:
mongos> use admin
mongos> db.createUser(
{
user: "admin",
pwd: "admin_password",
roles: [ { role: "userAdminAnyDatabase", db: "admin" } ]
} )
2015-01-13T22:19:53.882+0800 Error: couldn't add user: Could not lock auth data update lock.
at src/mongo/shell/db.js:1004
I did that according the mongodb website's documentation
can someone help me out? thanks in advance!

Create Superuser in mongo

I'm trying to create a user in mongo who can do anything in any db.
According to the guide I created a new admin: http://docs.mongodb.org/manual/tutorial/add-user-administrator
This is the code:
use admin
db.addUser( { user: "try1",
pwd: "hello,
roles: [ "userAdminAnyDatabase" ] } )
Then I stopped mongo, enabled the auth and restarted mongo.
Then I tried to create a database with his user.
According with this guide: http://www.mkyong.com/mongodb/how-to-create-database-or-collection-in-mongodb/
use fragola
db.users.save( {username:"fragolino"} )
And I get this: "not authorized for insert on fragola.users"
Anyone can help me?
from docs.mongodb.org-superuser-roles
Lets write answer that looks simple & also simple to implement
Steps :
1 : sudo apt-get install mongodb-org - in new terminal
2 : sudo mongod --port 27017 --dbpath /var/lib/mongodb
3 : mongo --port 27017 - in new terminal
4 : use admin
5 : As #drmirror said a user should have all 4 roles to be superuser
For Mongo Version 2.
db.createUser(
{
user: "tom",
pwd: "jerry",
roles: [
{ role: "userAdminAnyDatabase", db: "admin" },
{ role: "readWriteAnyDatabase", db: "admin" },
{ role: "dbAdminAnyDatabase", db: "admin" },
{ role: "clusterAdmin", db: "admin" }
]
})
For Mongo Version 3.
db.createUser(
{
user: "tom",
pwd: "jerry",
roles:["root"]
})
6 : sudo /etc/init.d/mongod stop OR sudo service mongod stop - in new terminal
7 : sudo /etc/init.d/mongod start OR sudo service mongod start
8 : restart your pc
9 : sudo mongod --auth --port 27017 --dbpath /var/lib/mongodb - in new terminal
10: mongo --port 27017 -u "tom" -p "jerry" --authenticationDatabase "admin" - in new terminal
Note : step 10 is most important step .
it will give Output on terminal like
MongoDB shell version: 2.6.11
connecting to: 127.0.0.1:27017/test
>
The role userAdminAnyDatabase gives the user the ability to create users and assign arbitrary roles to them. Because of this, that user has the power to do anything on the database, because he can give anybody any permission (including himself).
However, the userAdminAnyDatabase role by itself doesn't allow the user to do anything else besides assigning arbitrary rights to arbitrary users. To actually do something on the database, that user needs to have the following additional roles:
readWriteAnyDatabase
dbAdminAnyDatabase
clusterAdmin
A user who has the above three rights and userAdminAnyDatabase is a true super-user and can do anything.