简体   繁体   English

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

[英]How to connect to MongoDB 3.2 in Java with username and password?

I'm using MongoDB 3.2 in my application. 我在我的应用程序中使用MongoDB 3.2。 The code below demonstrates database initialization logic: 下面的代码演示了数据库初始化逻辑

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);
}

This code works fine, now I want to introduce access level separation to database. 这段代码工作正常,现在我想引入访问级别分离到数据库。

The steps to do that: 这样做的步骤:

  1. Define users: 定义用户:

     use myAppDB db.createUser( { "user": "myAdmin", "pwd": "123090d1487dd4ab7", roles: [ "readWrite", "dbAdmin" ] } ) use myAppDB db.createUser( { "user": "guest", "pwd": "guest", roles: [ "read" ] } ) 
  2. Re-create the MongoDB 3.2 service in authentication mode: "C:\\Program Files\\MongoDB\\Server\\3.2\\bin\\mongod.exe" --install --dbpath=C:\\data\\db --logpath=C:\\data\\log\\log.txt --auth --service . 在身份验证模式下重新创建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 And run it. 并运行它。

  3. Change the mongoClientURI connection string to mongoClientURI连接字符串更改为

     String mongoClientURI = "mongodb://" + DB_SRV_USR + ":" + DB_SRV_PWD + "@" + DB_URL + ":" + DB_PORT; 

    where DB_SRV_USR = myAdmin and DB_SRV_PWD = 123090d1487dd4ab7 . 其中DB_SRV_USR = myAdminDB_SRV_PWD = 123090d1487dd4ab7

  4. Check the authenticated connection in IDEA's Mongo Explorer with the same credentials, everything is OK. 使用相同的凭据检查IDEA的Mongo Explorer经过身份验证的连接,一切正常。

  5. Execute my application and get exception Authentication failed . 执行我的应用程序并获取异常Authentication failed

My questions: 我的问题:

  1. How to connect to MongoDB 3.2 in Java with username and password? 如何使用用户名和密码连接到Java中的MongoDB 3.2? I saw a couple of examples but they are using deprecated methods. 我看了几个例子,但是他们使用了弃用的方法。
  2. Should I add my users to myAppDB or to admin table? 我应该将我的用户添加到myAppDB还是admin表? In some tutorials I saw that users are created in admin table is it a good idea or it worth to create users only in a database they are going to work with? 在一些教程中,我看到用户是在admin表中创建的,这是一个好主意还是值得在他们将要使用的数据库中创建用户?

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

(1) Use MongoCredential (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) Use MongoClientURI (2)使用MongoClientURI

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

There are some variant forms for using MongoCredential and MongoClientURI for different authentication mechanisms, check here for details 有一些变体形式可以将MongoCredential和MongoClientURI用于不同的身份验证机制,请在此处查看详细信息

As MarkusWMahlberg correctly noted, it is necessary to note the database name in the connection string. 正如MarkusWMahlberg正确指出的那样,有必要记下连接字符串中的数据库名称。

For instance: 例如:

String mongoClientURI = "mongodb://" + DB_SRV_USR + ":" + DB_SRV_PWD + "@" + DB_URL + ":" + DB_PORT + "/" + dbName;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM