Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Authentication during connection to MongoDB server instance using Java

Is it possible to make something like :

MongoClient mongo = new MongoClient(ip, port, usrName, password)

in JAVA similar to the MongoVUE or other SQL based databases' authentication method.

There the authentication is done during connection to DB instance.

I don't see an appropriate instance method in MongoClient java doc

And the way in Authentication (Optional) Official docs

doesn't fit my goals, because it requires to change all the existing query methods in my application which don't use authentication now.

The way in Authenticate to MongoDB with the Java Driver looks exactly what i need, but there's no com.mongodb.MongoCredential class in mongo 2.10.1 distribution.

like image 811
rok Avatar asked Feb 18 '14 16:02

rok


1 Answers

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 );
like image 186
Bob Kuhar Avatar answered Sep 22 '22 21:09

Bob Kuhar