简体   繁体   中英

MongoDB - Not Authorized to Execute Command

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! :)

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

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 technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM