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
author image

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities. Read all published posts by

Comments

avatar
3000
newest oldest most voted
ajit
Guest
ajit

Awesome is the word for this link and for this tutorial.
I appreciate that.
Thanks a lot 🙂

liudonghai
Guest
liudonghai

maven mongo-java-driver version ??
version???

Kuler Can
Guest
Kuler Can

Hello. Can I implement this example with JSF? And What I need to introduce?

youssef
Guest
youssef

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

Mohmed Alkadeem
Guest
Mohmed Alkadeem

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

Sandeep
Guest
Sandeep

Very nice tutorial mkyong, as always. One problem, when I tried to apply authentication to your previous mongo example (link: http://www.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.

book
Guest
book

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

}

trackback
MongoDB Authentication example

[…] Java MongoDB authentication example […]

supun
Guest
supun

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");
    }
Faisal Basra
Guest
Faisal Basra

How, we can build “App” bean in Spring? Want to do same stuff, but within Spring container.

Thanks

Harshit
Guest
Harshit

Another useful link i found Mongodb java utility