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());

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(
at com.mongodb.connection.DefaultAuthenticator.authenticate(
at com.mongodb.connection.InternalStreamConnectionInitializer.authenticateAll(
at com.mongodb.connection.InternalStreamConnectionInitializer.initialize(
at com.mongodb.connection.DefaultServerMonitor$
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(
at com.mongodb.connection.CommandHelper.receiveCommandResult(
at com.mongodb.connection.CommandHelper.executeCommand(
at com.mongodb.connection.SaslAuthenticator.sendSaslContinue(
at com.mongodb.connection.SaslAuthenticator.authenticate(
... 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;
    //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 *