通过身份验证连接到MongoDB失败

时间:2015-12-22 11:04:50

标签: java mongodb mongodb-java

我在版本3中使用MongoDB,我创建了一个名为'logMonitor'的数据库并创建了一个用户:

{
    "_id" : "logMonitor.log",
    "user" : "log",
    "db" : "logMonitor",
    "roles" : [
        {
            "role" : "readWrite",
            "db" : "logMonitor"
        }
    ]
}

当我使用用户“log”通过shell连接到数据库时,它返回success,就像这样:

  

[jboss @ chonggouapp mongodb] $ mongo logMonitor -u“log”-p“log”

     

MongoDB shell版本:3.0.6

     

连接到:logMonitor

然而,通过Java与以下代码的连接失败。

    ServerAddress addr = new ServerAddress("10.46.20.65", 27017);

    MongoCredential credential = MongoCredential.createMongoCRCredential(
            "log", "logMonitor", "log".toCharArray());

    MongoClientOptions options = MongoClientOptions.builder()
            .serverSelectionTimeout(1000)
            .build();
    MongoClient mongoClient = new MongoClient(addr, Arrays.asList(credential), options);

    MongoDatabase db = mongoClient.getDatabase("logMonitor");

    long c = db.getCollection("sysLog").count();

引发以下异常:

  

线程“main”中的异常com.mongodb.MongoTimeoutException:在等待与ReadPreferenceServerSelector {readPreference = primary}匹配的服务器后1000 ms后超时。群集状态的客户端视图是{type = UNKNOWN,servers = [{address = 10.46.20.65:27017,type = UNKNOWN,state = CONNECTING,exception = {com.mongodb.MongoSecurityException:Exception authenticating},由{com.mongodb引起.MongoCommandException:命令失败,错误18:服务器10.46.20.65:27017上的'auth failed'。完整的回复是{“ok”:0.0,“errmsg”:“auth failed”,“code”:18}}}]       at com.mongodb.connection.BaseCluster.createTimeoutException(BaseCluster.java:370)       在com.mongodb.connection.BaseCluster.selectServer(BaseCluster.java:101)       在com.mongodb.binding.ClusterBinding $ ClusterBindingConnectionSource。(ClusterBinding.java:75)       在com.mongodb.binding.ClusterBinding $ ClusterBindingConnectionSource。(ClusterBinding.java:71)       在com.mongodb.binding.ClusterBinding.getReadConnectionSource(ClusterBinding.java:63)       在com.mongodb.operation.CommandOperationHelper.executeWrappedCommandProtocol(CommandOperationHelper.java:65)       在com.mongodb.operation.CountOperation.execute(CountOperation.java:172)       在com.mongodb.operation.CountOperation.execute(CountOperation.java:43)       在com.mongodb.Mongo.execute(Mongo.java:738)       在com.mongodb.Mongo $ 2.execute(Mongo.java:725)       在com.mongodb.MongoCollectionImpl.count(MongoCollectionImpl.java:167)       在com.mongodb.MongoCollectionImpl.count(MongoCollectionImpl.java:147)       在com.baosight.bsfc4.mn.lg.utils.Test.main(Test.java:34)

谁能告诉我这是什么问题?我的java代码有问题吗?

感谢。

4 个答案:

答案 0 :(得分:2)

请改用class MainScene: CCNode { var myVariable: Float? func useVariable { // Use variable here and in other functions } } ,它应该为您创建正确的凭据。

答案 1 :(得分:1)

检查不同类型的方法:http://api.mongodb.com/java/current/com/mongodb/MongoCredential.html

尝试使用

createCredential(String userName, String database, char[] password)

而不是

createMongoCRCredential(String userName, String database, char[] password)

后者使用挑战 - 响应协议,可能不受MongoDB支持/授权。

String user="dfasdfgsdfg";
    String database="odhah";
    char[] password="dfgsdfg960".toCharArray();

    MongoCredential credential = MongoCredential.createCredential(user,
            database,
            password);
    MongoClient mongoClient = new MongoClient(new ServerAddress("125.025.125.2", 27017),
            Arrays.asList(credential));

    MongoDatabase db = mongoClient.getDatabase(database);
    MongoCollection<Document> collection = db.getCollection("names");
    System.out.println("connecting to host....."+mongoClient);
    System.out.println("connecting to database....."+collection);

    List<Document> foundDocument = collection.find(new Document("userId","124")).into(new ArrayList<Document>());
    for (int i=0;i<foundDocument.size();i++) {
        System.out.println(">>>"+foundDocument.get(i));

    }

答案 2 :(得分:0)

考虑到Authentication during connection to MongoDB server instance using Java的完整代码是:

    //config is a class populating DB properties and credentials from a properties file

  List<ServerAddress> serverAddresses = new ArrayList<>();
    for (String node: config.getNodes()){
        serverAddresses.add( new ServerAddress(node) );
    }
    List<MongoCredential> credentials = new ArrayList<>();
    credentials.add(
            MongoCredential.createCredential(
                    config.getUser(),
                    config.getDb(),
                    config.getPassword().toCharArray()
            )
    );
    MongoClient mongo = new MongoClient( serverAddresses, credentials );
    db = mongo.getDatabase("hippo_reporting");
    collection = db.getCollection(config.getCollection());
// Now, we can do inserts etc...

答案 3 :(得分:0)

解决方案:

需要为此用户提供dbAdmin角色

db.grantRolesToUser("Username", [{ "role" : "dbAdmin", "db" : "DBName" }])