Authentication when connecting to a MongoDB server instance using Java

Is it possible to do something like:

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

in JAVA similar to MongoVUE or other SQL-based database authentication methods.

There authentication is performed while connecting to the DB instance.

I do not see a suitable instance method in MongoClient java doc

And the path to Authentication (optional) Official documents

doesn’t meet my goals because it requires changing all existing request methods in my application that no longer use authentication.

The method in "Authenticate to MongoDB using the Java driver" looks exactly what I need, but there is no com.mongodb.MongoCredential class in the mongo 2.10.1 distribution.

+4
source share
2 answers

You do not need to change all existing requests, you only need to change the logic that sets up your MongoClient. Most applications do this as a kind of Singleton, so adding authentication is just a matter of modifying Singleton. This is a pain in essence, that there is no signature that takes only String, String for the user's password, but its Mongo Java API gets used to disappointment.

MongoURI, ...

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

<MongoCredential>

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 );
+18

, Mongo3 SHA1 , . :

...
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 );
+1

Source: https://habr.com/ru/post/1527557/


All Articles