How can I authenticate any database with given username and password in Mongo Java Driver 2.13.0?

天涯浪子 提交于 2019-12-11 02:23:38

问题


Previously I could use db.authenticate(String username, char[] password) method. With 2.13.0, how can I achieve this?


回答1:


There is no replacement for db.authenticate(). The driver will use the credentials provided and make sure the connections are authenticated as they are created.

Based on this mongodb-user discussion the Java Driver team is open to discussions on what the real need for the db.authenticate(...) method.




回答2:


Use

import com.mongodb.MongoCredential;

MongoCredential mongoCred = MongoCredential.createMongoCRCredential(String username, String dbName, char[] password);

and create mongoclient using mongocredentials

com.mongodb.MongoClient.MongoClient(List seeds, List credentialsList, MongoClientOptions options)




回答3:


We can have user-password based authentication for databases, in that case we need to provide authorization credentials like below for new version.

MongoCredential journaldevAuth = MongoCredential.createPlainCredential("pankaj", "journaldev", "pankaj123".toCharArray());
    MongoCredential testAuth = MongoCredential.createPlainCredential("pankaj", "test", "pankaj123".toCharArray());
    List<MongoCredential> auths = new ArrayList<MongoCredential>();
    auths.add(journaldevAuth);
    auths.add(testAuth);

    ServerAddress serverAddress = new ServerAddress("localhost", 27017);
    MongoClient mongo = new MongoClient(serverAddress, auths);

If you are using older versions, you need to provide authentication details after getting the DB object like below

MongoClient mongo = new MongoClient("localhost", 27017);
DB db = mongo.getDB("journaldev");
boolean auth = db.authenticate("pankaj", "pankaj123".toCharArray());


来源:https://stackoverflow.com/questions/29343795/how-can-i-authenticate-any-database-with-given-username-and-password-in-mongo-ja

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!