"not authorized" error while querying from mongo shell, working fine from RoboMongo

1.2k Views Asked by At

I created a user, "test_user" on mongodb for db "test_db" and granted the readWrite role as follows

db.createUser(
   {
      user : "test_user",
      pwd : "password",
      roles : [
        {
           role : "readWrite",
           db : "test_db"
        }
     ]
  }
)

Mongo says Successfully added user

All is well, I connect to my db with RoboMongo and am able to create and list collections.

But when I connect to mongo using shell from my machine as follows

mongo -u 'test_user' --authenticationDatabase 'test_db' -p 'password'

I am not able to list or create collections. Mongo says

 E QUERY    [thread1] Error: listCollections failed: {
    "ok" : 0,
    "errmsg" : "not authorized on test to execute command { listCollections: 1.0, filter: {} }",
    "code" : 13,
    "codeName" : "Unauthorized"
}

when I type show collections in shell.

What am I missing ?

2

There are 2 best solutions below

0
On

The --authenticationDatabase only specifies the database where the MongoDB user needs to be authenticated against in order to log in. In other words, the database where the user was created on.

And because you created a user only with access to the test_db, you won't be authorized to run commands on other databases like the default test database when logging in with MongoDB using your created user.

You should have used this command if you wanted to be switched to the test_db after login:

mongo test_db -u 'test_user' --authenticationDatabase 'test_db' -p 'password'

0
On

Strange, I had to type use test_db in mongo shell to select the database before trying to list collections or query. Even though I had --authenticationDatabase param in my login script, mongo does not automatically choose the mentioned db for you. You have to do it yourself.