By default, MongoDB is run in trusted environment (authenticate with username and password is NOT require). In this tutorial, we show you how to start MongoDB in secure mode (authentication access is require), and uses Java driver to connect MongoDB with provided username and password.

1. Start MongoDB in Secure Mode

Create an user “mkyong” in MongoDB database “yourdb”.

> use yourdb
> db.addUser("mkyong","password")

To start mongoDB in secure mode, just provide the “–auth” argument.

> mongod --auth

Now, the MongoDB is started in secure /authentication mode (authenticate with username and password is require).

2. Testing

Try it with db.auth() method, 0 = failed, 1 = success.

> db.auth("mkyong","password")
1
> db.auth("mkyong","wrong password")
0

3. Java connect MongoDB

In Java, you can use “db.authenticate” to handle the MongoDB authentication.

DB db = mongo.getDB("yourdb");
boolean auth = db.authenticate("mkyong", "password".toCharArray());

If username and password is valid, “auth” will be true, else it will be false and return the following error pattern

com.mongodb.MongoException: unauthorized db:yourdb lock type:-1 client:192.168.1.3
	at com.mongodb.MongoException.parse(MongoException.java:82)
	at com.mongodb.DBApiLayer$MyCollection.__find(DBApiLayer.java:302)
	at com.mongodb.DBCursor._check(DBCursor.java:354)
	at com.mongodb.DBCursor._hasNext(DBCursor.java:484)
	at com.mongodb.DBCursor.hasNext(DBCursor.java:509)
	at com.mkyong.core.App.main(App.java:44)

Full Java example to connect MongoDB in secure mode.

package com.mkyong.core;
 
import java.net.UnknownHostException;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.Mongo;
import com.mongodb.MongoException;
 
/**
 * Java + MongoDB in Secure Mode
 * 
 */
public class App {
	public static void main(String[] args) {
 
		try {
 
			Mongo mongo = new Mongo("localhost", 27017);
			DB db = mongo.getDB("yourdb");
 
			boolean auth = db.authenticate("mkyong", "password".toCharArray());
 
			DBCollection collection = db.getCollection("yourCollection");
 
			System.out.println("Done");
 
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (MongoException e) {
			e.printStackTrace();
		}
 
	}
}

References

  1. https://jira.mongodb.org/browse/JAVA-45
  2. MongoDB Java Authentication
  3. MongoDB Security and Authentication
Note : You can find more similar articles at - Java MongoDB Tutorials