MongoDB + Java:用户文档中缺少凭据

时间:2015-12-04 08:58:30

标签: java mongodb authentication database

使用正确的现有数据库登录凭据,Java中的MongoDB连接测试失败。显示Load

这可能是不同版本的MongoDB之间的不匹配,因为我使用的是为 2.6 版本编写的代码,并使用版本 3 运行它。它不太可能介于不同版本的MongoDB驱动程序之间,因为我使用的是与测试代码相同的版本(com.mongodb.CommandFailureException)。

如何修复此错误并使其与一系列MongoDB版本兼容?

mongo-java-driver 2.12.4

String dbName = "test_db"; String host = "localhost"; Integer port = 27017; String username = "admin"; String password = "password"; static Logger log = Logger.getLogger(MongoTest.class.getName()); log.debug("DBNAME:"+dbName+"\nHOST:"+host+"\nPORT:"+port+"\nUSERNAME:"+username+"\nPASSWORD:"+password+"\n"); MongoCredential credential = MongoCredential.createMongoCRCredential(username, dbName, password.toCharArray()); List<MongoCredential> auths = new ArrayList<MongoCredential>(); auths.add(credential); MongoClient mongo = new MongoClient(new ServerAddress(host, port), auths); DB db = mongo.getDB(dbName); log.debug("DB:"+db); // not null DBCollection dbCollection = db.createCollection("__test__", new BasicDBObject()); // FAIL

mongo.log

例外:

2015-12-04T15:55:36.148+0100 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:7273 #79 (18 connections now open)
2015-12-04T15:55:36.242+0100 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:7274 #80 (19 connections now open)
2015-12-04T15:55:36.256+0100 I ACCESS   [conn80]  authenticate db: test_db { authenticate: 1, user: "admin", nonce: "xxx", key: "xxx" }
2015-12-04T15:55:36.258+0100 I ACCESS   [conn80] Failed to authenticate admin@test_db with mechanism MONGODB-CR: AuthenticationFailed MONGODB-CR credentials missing in the user document
2015-12-04T15:55:36.265+0100 I NETWORK  [conn80] end connection 127.0.0.1:7274 (18 connections now open)
2015-12-04T15:55:36.282+0100 I NETWORK  [initandlisten] connection accepted from 127.0.0.1:7275 #81 (19 connections now open)
2015-12-04T15:55:36.301+0100 I NETWORK  [conn79] end connection 127.0.0.1:7273 (18 connections now open)
2015-12-04T15:55:36.301+0100 I NETWORK  [conn81] end connection 127.0.0.1:7275 (18 connections now open)

1 个答案:

答案 0 :(得分:0)

通过在Mongo(3.0.7)CLI中正确添加用户来解决问题,我尝试在admin数据库上运行它,而它应该在test_db数据库上:

mongo --authenticationDatabase db_name -u username -p password
(Connected to Mongo CLI client...)
> use test-db;
> db.createUser( 
  { 
    "user" : "admin", 
    "pwd": "password",  
    "roles" : [      
      { role: "root", db: "admin" },
      { role: "readWrite", db: "admin" }, 
      { role: "dbAdmin", db: "admin" },
      { role: "readWrite", db: "test_db" }, 
      { role: "dbAdmin", db: "test_db" }
    ]  
});
(Success...)
> db.auth("admin","password")
1