Search code examples
javamongodbmongodb-authentication

MongoDB raw java connection


I am trying to create a generic mongo connection component that will be used with different mongo DB instances. I managed to make it work with some code like:

  // Creating a Mongo client 
  MongoClient mongo = new MongoClient( "localhost" , 27017 ); 

  // Creating Credentials 
  MongoCredential credential; 
  credential = MongoCredential.createCredential("sampleUser", "myDb", 
     "password".toCharArray()); 
  System.out.println("Connected to the database successfully");  
  
  // Accessing the database 
  MongoDatabase database = mongo.getDatabase("myDb"); 
  System.out.println("Credentials ::"+ credential); 

I don't understand why it needs to specify the database in 2 places: "myDb", once in the credential, and once while it does a getDatabase. More than that on my setup I need to specify a different DB on createCredential: "admin" in order to work. Why is the credential database different than the one I will run the query?


Solution

  • When you inspect the code deeper, you will find the below compelling reasons.

    This is the place where all the authenticators falls down.

    private void authenticateAll(final InternalConnection internalConnection, final ConnectionDescription connectionDescription) {
            if (connectionDescription.getServerType() != ServerType.REPLICA_SET_ARBITER) {
                for (final Authenticator cur : authenticators) {
                    cur.authenticate(internalConnection, connectionDescription);
                }
            }
        }
    

    authenticators contains list of credentials. There are four implementations.

    1. Default
    2. Native
    3. x509
    4. sasl

    "myDb", once in the credential - why

    Main reason to specify here, on which database the authenticate command has to be executed as each database can have different user name.

    executeCommand(getCredential().getSource(), authCommand, connection);
    

    once while it does a getDatabase - why

    It is altogether different. It returns MongoDatabase object which contains options to read, write concerns, list of collections, create view, create collection.