Skip to content
Advertisement

Java MongoDB Authentication Verification

I am trying to find a way to create a gui login for a database application that uses MongoDB. The server is 3.6 and the Java driver is 4.1.1. I can connect to the database and perform all CRUD operations via the application. I’m getting a little confused out how to write a simple authentication gui interface. It seems if I provide a bad username/password for access to the specific database, the main application still starts and it seems this is normal. I say normal because it doesn’t seem like there is any authentication until you actually perform an operation on the collection. At the login screen if I pass a bad user/pass I can execute a listcollectionsNames() but its not only until I attempt to get the most recent objectId from a collection that authentication occurs.

My assumption was that using:

public DB(String username, String passwd) {
    this.user = username;
    this.password = passwd.toCharArray();
    database = "test";
    
    System.out.println("Username = " + user);
    System.out.println("Password = " + Arrays.toString(password));
    
    credential = MongoCredential.createCredential(user, database, password);

    settings = MongoClientSettings.builder()
        .credential(credential)
        .applyToSslSettings(builder -> {
            builder.enabled(true);
            builder.invalidHostNameAllowed(false);
                })
        .applyToClusterSettings(builder -> 
            builder.hosts(Arrays.asList(new ServerAddress("host1", 27017))))
        .build();

    mongoClient = MongoClients.create(settings);

    MongoDataBase db = mongoClient.getDatabase(database);
    collection = db.getCollection("myTestCollection");
    System.out.println("Last record = " + getLastId());
    System.out.println("Current collections:n" + database.listCollectionNames());
}

Would fully authenticate a login, much like mongo shell would.

Searching the internet I have found examples such as:

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

But I can’t find anything similar to this command within the current driver.

Is the only way to verify authentication is to perform an operation and then pass that success/fail to the login gui?

Advertisement

Answer

Decided to just go with:

During the login process it performs the quickest operation (I think):

FindIterable<Document> cursor = collection.find().sort(new Document("_id", -1)).limit(1);

and then pass that success/fail to the login gui.

Advertisement