show dbs gives "Not Authorized to execute command" error - mongodb

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
})

Related

User with builtin "read" role still able to write/update documents in mongodb 5.0.8

I have a MongoDB v5.0.8 running with multiple databases. I switched to the required database (leaderboard-db) and added in a new user using the following commands from mongo shell:
Switched to the required DB:
use leaderboard-db
and
Created new user:
db.createUser({ user: "aa", pwd: "leaderboardadmin##!", roles: [ { role: "read", db: "leaderboard-db" } ], mechanisms: [ "SCRAM-SHA-256" ]})
Got success in user creation and can verify it by command
show users
Response:
{
"_id" : "leaderboard-db.aa",
"userId" : UUID("f571db84-cae4-4aac-b2f9-83b57094dd1b"),
"user" : "aa",
"db" : "leaderboard-db",
"roles" : [
{
"role" : "read",
"db" : "leaderboard-db"
}
],
"mechanisms" : [
"SCRAM-SHA-256"
]
}
I then use Studio 3T to connect to MongoDB with the user "aa". I should only be able to read the documents in the (leaderboard-db); however, I can also modify the document.
Screenshot of updating
Can anyone help resolve this, please?
I want to only allow the reading of documents for the user "aa". User "aa" should not have write access.
Thanks
Jack
As per recommendations from #WernfriedDomscheit, I was required to enable Authentication. I did that by updating the /etc/mongod.conf file, uncommented the Security section, added Authorization: enabled and restarting MongoDB by service mongod restart
That sorted it all and I was able to create users with different role-based access.
Life is good again.

mongo : not authorizeed on admin to execute on admin to execute command

I am new to Mongod, and have to get up a cluster. The db is started with --replSet=Data and I have created the cluster with rs.Initiate beforehand. But this question is about user administration.
This replica set was set up with this command:
rs.initiate({ _id : "Data",members: [
{ _id: 0, host: "srv1:27017" },
{ _id: 1, host: "srv2:27017" },
{ _id: 2, host: "srv3:27017" , arbiterOnly: true }
})
And the server was started with $ /usr/bin/mongod -f /etc/mongod.conf --replSet=rs0
Note that I have not yet configured the other nodes/added these into the cluster as far as I am aware, but I did distribute the keyFile: /etc/mongod/keyfile to each server.
An rs.status says it's not running.
> rs.Status();
{
"ok : 0"
"errmsg" : no replset config has been received",
"code" : 94,
"codename" : "NotYetInitialized"
}
I have run into some nib problems.
I created a user before called mgdb with the command :
# mongo admin -port 27017
> db.createUser ( {
user : 'mgdb', pwd: 'password', roles: [ { roles: root, db: admin } ]
})
This returned ok.
Next I tried with,
$ mongo --authenticationDatabase admin --username "mgdb" --password "password"
but got an error
E QUERY [js] Error authentication failed.
Next I tried to see the user list,
> show users;
not authorizeed on admin to execute on admin to execute command { UserInfo: 1.0}, lsid: { id: UID"xxxxxxxx") }. $db: "admin" } DB.prototy[e.getUsers#.....
So, I am bit lost. I used mysql a few years ago, but have not used it since. My dB experience is very little.
Although I can connect as the admin user, the admin user does not seem to have rights to do basic "show users;"
Where can I look in the dB to find out what went wrong?
Environment: RHEL 7.6 SELinux Enforcing, MOngdodB 4.2.9
In MongoDB you can create users per database. Usually users are create in database admin (I wouldn't know any reason to create them somewhere else):
use admin
db.createUser(...
or
db.getSiblingDB("admin").createUser(...
When you connect to Mongo then you need to specify the authentication database, i.e. the database where user was created:
mongo --usermame=mgdb --password 'password' --authenticationDatabase admin
See Authentication failure while trying to save to mongodb
In order to deploy a sharded cluster have a look at Deploy a Sharded Cluster or Deploy a Replica Set tutorial.

Mean Stack RockMongo on Google Cloud Platform

I have a Mean stack instance deployed on Google Cloud Platform, App Engine. I'm able to open an ssh tunnel and view rockmongo from a webbrowser:
http://127.0.0.1:8888/rockmongo/index.php?action=admin.index&host=0
I can login with root and default password from App Engine. When I go to add a new database it says it was successful but doesn't show the new database in the list. I create a new user and it shows that user. When I login through the command to mongo I can switch to my new database but when I try to find all items in a collection I get an error that the user isn't authorized to perform that action.
db.getCollection('users').find({})
Error: error: {
"ok" : 0,
"errmsg" : "not authorized on newdatabase to execute command { find: \"users\", filter: {} }",
"code" : 13
}
I added the readWrite role to the user and tried again, no luck. when I do a db.getUser("username") it returns "null".
What am I missing...
Figured it out, I had to:
Login as the root bitnami user
use admin
db.createUser( { user: "newusername",
pwd: "newpassword",
roles: [ "userAdminAnyDatabase","readWriteAnyDatabase" ]})
then
use newdatabase
db.createUser(
{
user: "newuser",
pwd: "newpassword",
roles: [ { role: "readWrite", db: "newdatabase" } ]
}
)
then the error went away. So more of an issue with mongo roles and permissions than bitnami and rockmongo. Still not sure why rockmongo never showed the new database from the php admin screen (all of this was done through the mongo command line).

MongoDB 3.2 - creating a CRUD admin for a certain database

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

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)