How to do authentication for MongoDB in Java

Here in this article we will see how to perform MongoDB authentication in Java. The MongDB Java Driver version used is 3.0.0.

1) First create the ServerAddress instance

ServerAddress serverAddress = new ServerAddress("localhost", 27017);

2) Create MongoCredential instance by providing the username and password for your database

MongoCredential mongoCredential = MongoCredential.createCredential("user1", "demodb", "pwd1".toCharArray());

where
user1 is the username
demodb is the database name
pwd1 is the password

3) Create instance of MongoClient by using ServerAddress and MongoCredential

MongoClient mongoClient = new MongoClient(serverAddress, Arrays.asList(mongoCredential));

4) Get instance of MongoDatabase by providing the database name

MongoDatabase mongoDB = mongoClient.getDatabase("demodb");

where demodb is the database name

Start your MongoDB server in auth mode by using mongod --auth. Now, once you get the database instance you can perform operations on it.

In case the username or password provided does not match the DB credentials, it will throw MongoSecurityException

com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=null, userName='chikki', source='demodb', password=<hidden>, mechanismProperties={}}
at com.mongodb.connection.SaslAuthenticator.authenticate(SaslAuthenticator.java:61)
at com.mongodb.connection.DefaultAuthenticator.authenticate(DefaultAuthenticator.java:32)
at com.mongodb.connection.InternalStreamConnectionInitializer.authenticateAll(InternalStreamConnectionInitializer.java:99)
at com.mongodb.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:44)
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115)
at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:127)
at java.lang.Thread.run(Thread.java:745)
Caused by: com.mongodb.MongoCommandException: Command failed with error 18: 'Authentication failed.' on server localhost:27017. The full response is { "ok" : 0.0, "code" : 18, "errmsg" : "Authentication failed." }
at com.mongodb.connection.CommandHelper.createCommandFailureException(CommandHelper.java:168)
at com.mongodb.connection.CommandHelper.receiveCommandResult(CommandHelper.java:123)
at com.mongodb.connection.CommandHelper.executeCommand(CommandHelper.java:32)
at com.mongodb.connection.SaslAuthenticator.sendSaslContinue(SaslAuthenticator.java:99)
at com.mongodb.connection.SaslAuthenticator.authenticate(SaslAuthenticator.java:58)
... 6 more

3 thoughts on “How to do authentication for MongoDB in Java

  1. HI,

    When it throws the Exception, does it actually throw it? I can’t seem to catch it in my application using;
    try{
    //basic db operation
    } catch (MongoSecurityException mse) {
    System.err.println(“>>” + mse.getClass().getName() + “: ” + mse.getMessage());
    JOptionPane.showMessageDialog(null, “Invalid Credentials, login denied, security”);
    }

    Any ideas?

Leave a Reply

Your email address will not be published. Required fields are marked *