Authentication during connection to MongoDB server instance using Java

天涯浪子 提交于 2019-11-29 07:13:49

You shouldn't need to change all your existing queries, you should only need to change the logic that establishes your MongoClient. Most applications do this as some sort of Singleton so adding authentication is just a matter of modifying the Singleton. It is a pain-in-the-butt that there isn't a signature that takes just String, String for username password, but its the Mongo Java API, get used to disappointment.

You can either go the MongoURI path which gets you the shortest signature...

MongoClient mongo = new MongoClient(
  new MongoClientURI( "mongodb://app_user:bestPo55word3v3r@localhost/data" )
);

Or go with the more verbose List<MongoCredential> path

List<ServerAddress> seeds = new ArrayList<ServerAddress>();
seeds.add( new ServerAddress( "localhost" );
List<MongoCredential> credentials = new ArrayList<MongoCredential>();
credentials.add(
    MongoCredential.createMongoCRCredential(
        "app_user",
        "data",
        "bestPo55word3v3r".toCharArray()
    )
);
MongoClient mongo = new MongoClient( seeds, credentials );
theINtoy

Following on from Bob Kuhar's accepted answer, in Mongo3 the mechanism has change to SHA1 from challenge response as shown in the code snippet. I need to update the code snippet as follows:

...
import com.mongodb.MongoClient;
import com.mongodb.MongoCredential;
import com.mongodb.ServerAddress;
...

// Manage the mongo db connection...
List<ServerAddress> seeds = new ArrayList<ServerAddress>();
seeds.add( new ServerAddress(configuration.getMongoHost(), configuration.getMongoPort() ));
List<MongoCredential> credentials = new ArrayList<MongoCredential>();
credentials.add(
    MongoCredential.createScramSha1Credential(
        configuration.getMongoUser(),
        configuration.getMongoDb(),
        configuration.getMongoPassword().toCharArray()
    )
);
MongoClient mongo = new MongoClient( seeds, credentials );
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!