Friday, March 22, 2013

Authentication to MongoDb using Java

MongoDB provides basic support for authentication with the auth setting. For multi-instance deployments (i.e. replica sets, and sharded clusters) use the keyFile setting, which implies auth, and allows intra-deployment authentication and operation. Be aware of the following behaviors of MongoDB’s authentication system:

Enable auth settings to MongoDb requires few steps:
Invoke addUser command on mongo shell:


Start the mongod in --auth mode as shown


Check whether auth setting are working


Now test with the java program to authenticate the database in trusted enviornment.
package com.rajkrrsinghblogspot;

import java.net.UnknownHostException;

import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.MongoClient;
import com.mongodb.ServerAddress;

public class MongoAuth {

public static void main(String[] args) {
try {
MongoClient client = new MongoClient(new ServerAddress("localhost", 27017));

DB database = client.getDB("blog");
boolean auth = database.authenticate("rajkumar", "password".toCharArray());
DBCollection collection = database.getCollection("posts");

if(auth){  
   System.out.println("Authentication is Successful");  
   BasicDBObject query = new BasicDBObject().append("author", "rajkumar");
   BasicDBObject projection = new BasicDBObject().append("author", true);
   DBObject doc = collection.findOne(query,projection);
   System.out.println(doc.toString());
  }else{  
   System.out.println("Authentication is UnSuccessful");  
  }  

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




}

}