Main Tutorials

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

About Author

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

Comments

Subscribe
Notify of
13 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
ajit
10 years ago

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

nitesh
1 year ago

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 .

Thunderarea
3 years ago

Thanks for all your articles. Are very useful! However this article need to be revised as the method authenticate is deprecated. Thanks!
https://api.mongodb.com/java/2.13/com/mongodb/DB.html
https://mongodb.github.io/mongo-java-driver/3.4/driver/tutorials/authentication/

liudonghai
6 years ago

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

Kuler Can
6 years ago

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

youssef
6 years ago

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
8 years ago

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
10 years ago

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.

book
10 years ago

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

}

supun
11 years ago

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
11 years ago

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

Thanks

Harshit
12 years ago

Another useful link i found Mongodb java utility