如何使用用户名和密码连接到Java中的MongoDB 3.2?

问题描述 投票:6回答:2

我在我的应用程序中使用MongoDB 3.2。下面的代码演示了数据库初始化逻辑

private void dbInit(String dbName) {

    String mongoClientURI = "mongodb://" + DB_URL + ":" + DB_PORT;
    MongoClientURI connectionString = new MongoClientURI(mongoClientURI);

    // enable SSL connection
    MongoClientOptions.builder().sslEnabled(true).build();

    if (this.mongoClient == null) {
        this.mongoClient = new MongoClient(connectionString);
    }

    // create database if doesn't exist
    this.mongoClient.getDatabase(dbName);
}

这段代码工作正常,现在我想引入访问级别分离到数据库。

这样做的步骤:

  1. 定义用户: use myAppDB db.createUser( { "user": "myAdmin", "pwd": "123090d1487dd4ab7", roles: [ "readWrite", "dbAdmin" ] } ) use myAppDB db.createUser( { "user": "guest", "pwd": "guest", roles: [ "read" ] } )
  2. 在身份验证模式下重新创建MongoDB 3.2服务:"C:\Program Files\MongoDB\Server\3.2\bin\mongod.exe" --install --dbpath=C:\data\db --logpath=C:\data\log\log.txt --auth --service。并运行它。
  3. mongoClientURI连接字符串更改为 String mongoClientURI = "mongodb://" + DB_SRV_USR + ":" + DB_SRV_PWD + "@" + DB_URL + ":" + DB_PORT; 其中DB_SRV_USR = myAdminDB_SRV_PWD = 123090d1487dd4ab7
  4. 使用相同的凭据检查IDEA的Mongo Explorer中经过身份验证的连接,一切正常。
  5. 执行我的应用程序并获得异常Authentication failed

我的问题:

  1. 如何使用用户名和密码连接到Java中的MongoDB 3.2?我看到了几个examples,但他们正在使用弃用的方法。
  2. 我应该将我的用户添加到myAppDBadmin表吗?在一些教程中,我看到用户是在admin表中创建的,这是一个好主意还是值得在他们将要使用的数据库中创建用户?
java mongodb authentication
2个回答
8
投票

使用mongodb-3.4.2和mongo-java-driver-3.4.2.jar进行测试

(1)使用MongoCredential

MongoCredential credential = MongoCredential.createCredential("user", "database", "passwd".toCharArray());
MongoClient mongoClient = new MongoClient(new ServerAddress("localhost", 27017), Arrays.asList(credential));
MongoDatabase db = mongoClient.getDatabase( "test" );
MongoCollection collection = db.getCollection("mycol");
FindIterable fi = collection.find();
MongoCursor cursor = fi.iterator();

(2)使用MongoClientURI

MongoClientURI uri = new MongoClientURI("mongodb://user:passwd@localhost:27017/?authSource=test");
MongoClient mongoClient = new MongoClient(uri);

有一些变体形式可以将MongoCredential和MongoClientURI用于不同的身份验证机制,请查看here以获取详细信息


0
投票

正如MarkusWMahlberg正确指出的那样,有必要记下连接字符串中的数据库名称。

例如:

String mongoClientURI = "mongodb://" + DB_SRV_USR + ":" + DB_SRV_PWD + "@" + DB_URL + ":" + DB_PORT + "/" + dbName;
© www.soinside.com 2019 - 2024. All rights reserved.