MongoDB - Not Authorized to Execute Command

Help picture Help · Jan 3, 2019 · Viewed 22.2k times · Source

I have successfully enabled authorization on MongoDB and I have created an account on the admin database and then I created an account for my database called test. The following connection string to connect to my test database works successfully: mongo --host 192.168.17.52 --port 27017 -u user1 -p password --authenticationDatabase test

Only problem I have now is, I cannot execute commands such as: show dbs. I get the following error when I try to do so:

"errmsg" : "not authorized on admin to execute command { listDatabases: 1.0, lsid: { id: UUID(\"a1d5bc0d-bc58-485e-b232-270758a89455\") }, $db: \"admin\" }"

I have been on many online sources to help fix this issue but no luck, is there a way to resolve this issue? Seems like my user can't access the admin database, is there a way to grant this access to my user so I can run the necessary commands like show dbs?

Any help is much appreciated! :)

Answer

nabeel picture nabeel · Jun 28, 2019

In order to run show dbs command and if the user has access to multiple databases, first the user should be created on the admin database (this is because listDatabases action is a cluster wide operation). Also the user should be given access to this operation. In order to do that, a new role should be created with the action. Below are the steps for the same:

//login as admin with --authenticationDatabase "admin" (assumption is that admin user is with root privileges) and then run the below:

use admin;

db.runCommand({ createRole: "listDatabases", privileges: [{ resource: { cluster : true }, actions: ["listDatabases"]} ], roles: [] });

db.createUser({user:"testUser", pwd:"passwd", roles:[{role:"read", db:"db1"},{role:"read", db:"db2"},{ role: "listDatabases", db: "admin" }]});

//exit as admin user and login as testUser: note the --authenticationDatabase "admin"

mongo -u "testUser" -p --authenticationDatabase "admin"

after logging in run the command below and it should list all the databases:

show dbs;

The below will work fine even though user is not given access to admin database:

use admin;

But then the below will give error:

show collections;