Java MongoDB : Authentication example

By default, MongoDB is run in trust environment (authentication with a username and password is NOT required). In this tutorial, we will show you how to start MongoDB in secure mode / enable authentication, and connect with the Java MongoDB driver.

1. Start MongoDB in Secure Mode

Start MongoDB with --auth option, now, MongoDB need username and password to perform any database / collection operations.


mongod --auth

Later, we need to connect to the database “testdb”, so add a user for testing later.


> use admin
> db.addUser("admin","password")
> use testdb
> db.addUser("mkyong","password")

To enable MongoDB authentication, you must first add a user to the special “admin” database, please refer to this MongoDB authentication example for detail guide.

2. Java + MongoDB Authentication example

If MongoDB is started in secure mode, below “insert” operation is no longer valid, and prompts “need to login” error message.


	Mongo mongo = new Mongo("localhost", 27017);
	DB db = mongo.getDB("testdb");

	DBCollection table = db.getCollection("user");

	BasicDBObject document = new BasicDBObject();
	document.put("name", "mkyong");
	table.insert(document);

com.mongodb.CommandResult$CommandFailure: command failed [getlasterror]: 
	{ "serverUsed" : "localhost/127.0.0.1:27017" , "errmsg" : "need to login" , "ok" : 0.0}
	
	at com.mongodb.CommandResult.getException(CommandResult.java:88)
	at com.mongodb.CommandResult.throwOnError(CommandResult.java:134)
	at com.mongodb.DBTCPConnector._checkWriteError(DBTCPConnector.java:142)
	at com.mongodb.DBTCPConnector.say(DBTCPConnector.java:183)
	at com.mongodb.DBTCPConnector.say(DBTCPConnector.java:155)
	at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:270)
	at com.mongodb.DBApiLayer$MyCollection.insert(DBApiLayer.java:226)
	at com.mongodb.DBCollection.insert(DBCollection.java:75)
	at com.mongodb.DBCollection.insert(DBCollection.java:59)
	at com.mongodb.DBCollection.insert(DBCollection.java:104)
	at com.mkyong.core.App.main(App.java:40)

Now, using db.authenticate() to perform the authentication, a return value of true = success, false = fail.


package com.mkyong.core;

import java.net.UnknownHostException;
import java.util.Date;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
import com.mongodb.MongoException;

/**
 * Java + MongoDB in Secure Mode
 * 
 */
public class JavaMongoDBAuthExample {
   public static void main(String[] args) {

    try {

	Mongo mongo = new Mongo("localhost", 27017);
	DB db = mongo.getDB("testdb");
			
	boolean auth = db.authenticate("testdb", "password".toCharArray());
	if (auth) {
			
		DBCollection table = db.getCollection("user");

		BasicDBObject document = new BasicDBObject();
		document.put("name", "mkyong");
		table.insert(document);
	
		System.out.println("Login is successful!");
	} else {
		System.out.println("Login is failed!");
	}
	System.out.println("Done");

    } catch (UnknownHostException e) {
	e.printStackTrace();
    } catch (MongoException e) {
	e.printStackTrace();
    }
  }
}

References

  1. Java MongoDB authentication example
  2. JIRA – DB.authenticate() should use a char[] for the password
  3. MongoDB Java Authentication example
  4. MongoDB Security Practices and Management

13 comments on “Java MongoDB : Authentication example

  1. Hi ,

    I want to update the mongodb uri password where the password i am fetching from some other system , and the uri is configured in properties file , I only need to update the password in properties file
    , is there a way where i can update the uri password during application initilaization .

  2. i put that code in android studio and it dont work , he stop the application whene i execute this code in a bouton
    do you have a solution pliz how to put information in mongodb in android studio

  3. I try to implement this command”db.oplog.rs.find() ” but it shows me nothing.
    I want to implement this command to shows the provenance information.
    I work on Mongodb on windows 8.1.
    please could you tell me what is problem?
    Thank you

  4. Very nice tutorial mkyong, as always. One problem, when I tried to apply authentication to your previous mongo example (link: https://mkyong.com/mongodb/java-mongodb-get-collection-from-database/), it failed. Exception: com.mongodb.MongoException: not authorized for query on yourdb.system.namespaces.

    I don’t think this is caused by user not being authorized to list collections, because if call db.getCollectionNames() on the mongo shell (using the same user credentials) it works fine. Could it be a bug in mongo Java driver?

    Thanks.

  5. I want to know when for the no-auth user, when will happen in the else path in below code here?
    boolean auth = db.authenticate(“testdb”, “password”.toCharArray());
    if (auth) {

    DBCollection table = db.getCollection(“user”);

    BasicDBObject document = new BasicDBObject();
    document.put(“name”, “mkyong”);
    table.insert(document);

    System.out.println(“Login is successful!”);
    } else {
    DBCollection table = db.getCollection(“user”);

    BasicDBObject document = new BasicDBObject();
    document.put(“name”, “mkyong”);
    table.insert(document);

    }

  6. For Beginners, I added this to check the wrong authentication. 😀

     
        Mongo mongo = new Mongo("127.0.0.1",27017);
        DB db = mongo.getDB("myauthdb");
    			
        boolean auth = db.authenticate("supun", "pasdds123".toCharArray());
    			
        System.out.println(auth);
        if(auth){
    	DBCollection collection = db.getCollection("technodyne");		
    	System.out.println("DONE AUTHENTICATION!");}
        else{
    	System.out.println("Wrong AUTHENTICATION");
        }
    

Leave a Comment

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