sak91
sak91

Reputation: 23

not authorized for query on databasename.collection on mongodb using eclipse

I gave role for DB purp is UserAdmin,I run server with mongod --auth --dbpath c:\mongodb\data\db. First I done a java file in eclipse to connect DB,it worked properly.

After I create and run the below file in eclipse:

try {

    MongoClient mongoClient = new MongoClient("localhost", 27017);
    DB db = mongoClient.getDB("purplista");
    boolean auth =db.authenticate("purp","123".toCharArray());
    System.out.println("Connect to database successfully");

    DBCollection doc = db.getCollection("test");
    System.out.println("Collection test selected successfully..");

    DBCursor cursor = doc.find();
    while (cursor.hasNext()) {
        System.out.println(cursor.next());
    }
   }  catch (Exception e) {
e.printStackTrace();

}

got error like this:

Connect to database successfully..

Collection test selected successfully..

com.mongodb.MongoException: not authorized for query on purplista.test at com.mongodb.QueryResultIterator.throwOnQueryFailure(QueryResultIterator.java:214) at com.mongodb.QueryResultIterator.init(QueryResultIterator.java:198) at com.mongodb.QueryResultIterator.initFromQueryResponse(QueryResultIterator.java:176) at com.mongodb.QueryResultIterator.(QueryResultIterator.java:64) at com.mongodb.DBCollectionImpl.find(DBCollectionImpl.java:80) at com.mongodb.DBCollectionImpl.find(DBCollectionImpl.java:61) at com.mongodb.DBCursor._check(DBCursor.java:458) at com.mongodb.DBCursor._hasNext(DBCursor.java:546) at com.mongodb.DBCursor.hasNext(DBCursor.java:571) at purplista.FindDoc.main(FindDoc.java:34)

Upvotes: 2

Views: 5852

Answers (1)

aks
aks

Reputation: 720

A couple of issues I see are:

  1. You are not checking the return value of db.authenticate() which may be returning false if it fails to authenticate.
  2. Even if authenticated, you may not have appropriate permissions to perform the intended operations (in your case read) on the specified database.

A few things to check:

  1. Is this a valid user / password - may be try mongo shell using the same credentials
  2. If valid, does it have appropriate permissions on the database you are using? Since you can create users in "admin" database that can be used to authenticate, however those users may not be setup for additional access that you need for your operations.
  3. If you are using MongoDB v2.6, all the users must be in "admin" database.
  4. You can check for "system.users" collection under the database of interest (test) and admin database to check where the user is setup.

Upvotes: 2

Related Questions