MongoDB not authorized for query - code 13 - mongodb

In MongoDB 2.6.1 I've setup a user with dbAdmin rights:
{
"_id" : "mydbname.myusername",
"user" : "myusername",
"db" : "mydbname",
"credentials" : {
"MONGODB-CR" : "<some credentials>"
},
"roles" : [
{
"role" : "dbAdmin",
"db" : "mydbname"
}
]
}
When I use the mongo shell to connect to the database (using -u and -p on command line) and run a query like this:
db.mycollectionname.find()
I get this error:
error: { "$err" : "not authorized for query on mydbname.request", "code" : 13 }
Any ideas what can be happening?
So far I've tried adding every role I can find to the user but that hasn't helped.

You need to assign the read role to the user in question.
The dbAdmin role does not include read access on non-system collections.

For anybody running into this problem against Mongo 3.0.6, I fixed by adding
?authMode=scram-sha1
at the end of my mongodb uri.
Here are some docs explaining the purpose of scram-sha1

In addition to #Sebastian's answer, that means explicitely:
Grant a Role
Grant a role using the db.grantRolesToUser() method. For example, the
following operation grants the reportsUser user the read role on the
accounts database:
db.grantRolesToUser(
"your_user",
[
{ role: "read", db: "your_db" }
]
)

I’m posting this because I had trouble finding this solution online. The problem is embarrassing but the error message and scenario make it somewhat difficult to figure out so I'm hoping to save someone some pain.
My application was able to establish a database connection, start and serve static pages but every time it tried to execute a query I got this error.
MongoError: not authorized on mydb to execute command { count: "urls", query: {} }
This error was caused by a userid and password with the wrong separator
mongodb://myuserid/mypassword#ds112345.mlab.com:12345/mydb [wrong]
mongodb://myuserid:mypassword#ds112345.mlab.com:12345/mydb [right]
While the node application was able to successfully connect to MongoDB, the incorrectly formatted URI caused the driver to skip authentication prior to issuing database commands.
Thanks and a hat tip to the people at mLab support.

In my case helped to add ?authSource=admin to uri.
So the uri looked like this:
spring.data.mongodb.uri=mongodb://user:password#host:port/database?authSource=admin

I was getting error like
err { MongoError: not authorized on XXXX to execute command { $eval: function(){ return db.tbl_user.find( {
For me role executeFunctions worked. Once you give role your user should look like following...
{
"_id" : "XXXXX",
"user" : "USERXXX",
"db" : "DBXXXX",
"roles" : [
{
"role" : "executeFunctions",
"db" : "admin"
},
{
"role" : "dbOwner",
"db" : "fryendsapp"
}
]
}

I had the same problem, after a lot of trial and error I solved it by adding the role "read" to my user but indicating the database as well:
db.grantRolesToUser("myUserName",
[{ role: "read", db: "myDataBaseName"}] );
Greetings

I was having the same problem until I realized I made a mistake. I was inheriting a mongo client pointing to a different database from a parent Perl class without realizing it. Maybe something you can check.

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.

Specific document for every user

I'm new in MongoDB and I just can not understand how the database works to the end. For a start, I'll explain what I want to do. It is necessary to make a form on the site through which new users will be added for the client program on WPF.NET in which the connection to the server will occur.
It is not clear to me where the user should be in the database in admin or in my database, what is it local, config dbs?
I watched the video and read for the authentification. Okay, I created the user, but it connects to the whole database, and so can read the data of another user. I mean that if someone wants to go to the server and hack into or overwrite the data of another client. Is it possible to give the client access to only a specific document?
Example:
Users: ClientUser1, ClientUser2, ClientUser3
Collection ClientCollection: Document1ForUser1Only, Document2ForUser2Only, Document3ForUser3Only
C# WPF .NET Client I Call
new MongoClient("mongodb://127.0.0.1:27017/?db=custom&user=ClientUser1&password=1234"
Access only for Document1ForUser1Only, because is it correct user account data.
Update1
It seems to me that all this can be done through roles. I did my part and pointed it to the user. But when I do a search for my collections, it shows me a mistake. And in the program Studio 3T I do not see any collection.
db.createRole({ role: "User",
privileges: [
{ resource: { db: "testdb", collection: "UserCollection" }, actions: [ "find", "update", "insert", "remove" ]}
],
roles: []
})
> show collections
2018-05-13T20:38:09.463+0300 E QUERY [thread1] Error: listCollections failed: {
"ok" : 0,
"errmsg" : "not authorized on testdb to execute command {
listCollections: 1.0, filter: {}, $db: \"testdb\" }",
"code" : 13,
"codeName" : "Unauthorized"
} :
_getErrorWithCode#src/mongo/shell/utils.js:25:13
DB.prototype._getCollectionInfosCommand#src/mongo/shell/db.js:941:1
DB.prototype.getCollectionInfos#src/mongo/shell/db.js:953:19
DB.prototype.getCollectionNames#src/mongo/shell/db.js:964:16
shellHelper.show#src/mongo/shell/utils.js:813:9
shellHelper#src/mongo/shell/utils.js:710:15
#(shellhelp2):1:1

MongoDB shell authentication error

I created a user and password for a database called student.:
db.createUser({user:'Catalin',pwd:'Catalin',roles:[{role:'userAdmin',db:'student'}]});
So I restarted MongoDB Server with this command:
mongod --auth --dbpath C:\data\db
in another terminal, I connected to the sever with:
mongo
then queried the server with :
> db.getUsers()
[
{
"_id" : "student.Catalin",
"user" : "Catalin",
"db" : "student",
"roles" : [
{
"role" : "userAdmin",
"db" : "student"
}
]
}
]
went to the student database:
> use student
switched to db student
Entered my username and password succesfully via this command:
> db.auth('Catalin','Catalin');
1
and when I want to view my collections I get an error, WHY?:
> show collections
2016-03-07T15:54:41.166+0300 E QUERY [thread1] Error: listCollections failed:
{
"ok" : 0,
**"errmsg" : "not authorized on student to execute command { listCollectio
ns: 1.0, filter: {} }",**
"code" : 13
} :
_getErrorWithCode#src/mongo/shell/utils.js:23:13
DB.prototype._getCollectionInfosCommand#src/mongo/shell/db.js:746:1
DB.prototype.getCollectionInfos#src/mongo/shell/db.js:758:15
DB.prototype.getCollectionNames#src/mongo/shell/db.js:769:12
shellHelper.show#src/mongo/shell/utils.js:695:9
shellHelper#src/mongo/shell/utils.js:594:15
#(shellhelp2):1:1
"errmsg" : "not authorized on student to execute command { listCollectio
ns: 1.0, filter: {} }",
P.S. : I'm using mongoDB 3.2
The userAdmin built-in role only provides the ability to create and modify roles and users on a database. If you need access to the database, you would need to either assign database roles, or other roles that has database access such as dbOwner.
Please see Built-in Roles for more detailed information.
You may also find these useful:
Manage users and roles.
Enable client access control.
If you are using version 5 or befor DataBase MongoDB, pay attention to this point. You should not write anything in the mongod.conf file in the /etc/mongod.conf path. Use the following two commands to update the dependencies.
install dependencies :
sudo apt install libgconf-2-4
sudo add-apt-repository universe

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

dbowner "not authorized" to update user?

I'm trying to update the roles of a user.
So I tried the following command with the admin-user (which has the dbOwner and userAdmin priv. and is created directly on the UnitTestDb)
db.runCommand({ "updateUser" : "unittestuser1", "roles" : [{ "role" : "Testentity_readwrite", "db" : "UnitTestDb" }, { "role" : "Testentity_read", "db" : "UnitTestDb" }] }
I'm running this command directly on the "UnitTestDb" and the role "Testentity_read" is also directly created in this database.
I'm getting the following error:
{
"ok" : 0,
"errmsg" : "not authorized on UnitTestDb to execute command { updateUser: \"unittestuser1\", roles: [ { role: \"Testentity_readwrite\", db: \"UnitTestDb\" }, { role: \"Testentity_read\", db: \
"UnitTestDb\" } ] }",
"code" : 13
}
I am able to update the customData for the user but not the role...
Can someone tell me which privilege or role my admin user needs to execute this update?
dbOwner should have full access to database he was created on ( from mongodb.org: The database owner can perform any administrative action on the database. This role combines the privileges granted by the readWrite, dbAdmin and userAdmin roles.)
Tobias
I believe the issue is that updateUser requires additional rights on all databases. From the documentation:
Required Access
You must have access that includes the revokeRole action on all
databases in order to update a user’s roles array.
You must have the grantRole action on a role’s database to add a role
to a user.
Note the requirement for revokeRole on all databases, not just on the database involved.
I'd try using the db.grantRolesToUsers() command instead, as it does not require the same level of rights.
http://docs.mongodb.org/manual/reference/method/db.grantRolesToUser/
Required Access
You must have the grantRole action on a database to grant a role on
that database.
Alternatively you can make certain that user running the updateUser command has the revokeRole right on all databases.