MongoDB - Not Authorized to Execute Command MongoDB - Not Authorized to Execute Command shell shell

MongoDB - Not Authorized to Execute Command


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;


The problem is related the database you are using with the --authenticationDatabase parameter.

You are connecting to mongo with the user of your test database who has no privileges to execute listDatabase commands.

Let's do this using the admin db as auth db

mongo --host 192.168.17.52 --port 27017 -u user1 -p password --authenticationDatabase admin

and then run the command

show dbs