连接到Mongo时出现身份验证错误

时间:2015-06-30 17:12:34

标签: java spring mongodb authentication

连接到Mongo DB时出现异常:

下面是Stack Trace:

Exception in thread "main" com.mongodb.CommandFailureException: { "serverUsed" : "127.0.0.1:27017" , "ok" : 0.0 , "code" : 18 , "errmsg" : "Authentication failed."}
    at com.mongodb.CommandResult.getException(CommandResult.java:76)
    at com.mongodb.CommandResult.throwOnError(CommandResult.java:140)
    at com.mongodb.DBPort$SaslAuthenticator.authenticate(DBPort.java:899)
    at com.mongodb.DBPort.authenticate(DBPort.java:432)
    at com.mongodb.DBPort.checkAuth(DBPort.java:443)
    at com.mongodb.DBTCPConnector.innerCall(DBTCPConnector.java:293)
    at com.mongodb.DBTCPConnector.call(DBTCPConnector.java:273)
    at com.mongodb.DBCollectionImpl.find(DBCollectionImpl.java:84)
    at com.mongodb.DBCollectionImpl.find(DBCollectionImpl.java:66)
    at com.mongodb.DBCursor._check(DBCursor.java:498)
    at com.mongodb.DBCursor._hasNext(DBCursor.java:621)
    at com.mongodb.DBCursor.hasNext(DBCursor.java:657)
    at mongoOperations.mongoOperations.getConnectionMongo(mongoOperations.java:103)
    at mongoOperations.mongoOperations.main(mongoOperations.java:138)

以下是代码段:

private static void getConnectionMongo(){

    try{
        String uri = "mongodb://accountUser:password@127.0.0.1/test";
        MongoClientURI mongoClientURI = new MongoClientURI(uri);
        MongoURI mongoURI = new MongoURI(mongoClientURI);
        Mongo mongo = new Mongo(mongoURI);
        UserCredentials userCredentials = new UserCredentials("accountUser", "password");
        SimpleMongoDbFactory dbFactory =  new SimpleMongoDbFactory(mongo, "test", userCredentials);
        MongoTemplate mongoTemplate = new MongoTemplate(dbFactory);
        DBCollection collection = mongoTemplate.getCollection("table");
        DBCursor cursor =  collection.find();
        while(cursor.hasNext()){
            System.out.println(cursor.next());
        }
    }
    catch(UnknownHostException e){

    }
}

以下是mongo Shell的代码片段:

  

db.auth('accountUser','password');   1

这些是使用的jar文件: 弹簧数据的mongodb-1.3.0.RELEASE, 蒙戈-java的驾驶员2.13.2

任何建议都会很明显。谢谢!!

1 个答案:

答案 0 :(得分:0)

传递此URI

@Entity
// anything to add here?
public class SomeClass {

    // what do I need to add here?
    private java.net.URL myUrl;

    ...
}

或者将userCredentials传递给构造函数都不能一起使用,仍然可以突出显示它确实引发错误的哪一行

  1. String uri = "mongodb://accountUser:password@127.0.0.1/test";
  2. MongoTemplate mongoTemplate = new MongoTemplate(dbFactory);
  3. DBCollection collection = mongoTemplate.getCollection("table");