MongoClient mongoClient = new MongoClient(); DB db = mongoClient.getDB("test"); boolean auth = db.authenticate(myUserName, myPassword);If the name and password are valid for the database, auth will be true. Otherwise, it will be false. You should look at the MongoDB log for further information if available.
> use dineshonjavaDB > db.addUser("dineshonjava","password")
> mongod --auth2. Now, the MongoDB is started in secure /authentication mode (authenticate with username and password is require).
> db.auth("dineshonjava","password") 1 > db.auth("dineshonjava","password1") Error: { errmsg: "auth fails", ok: 0.0 } 0 >
DB db = mongo.getDB("dineshonjavaDB"); boolean auth = db.authenticate("dineshonjava", "password".toCharArray());
com.mongodb.MongoException: unauthorized db:dineshonjavaDB 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.dineshonjava.mongo.test.MongoAuthDemo.main(MongoAuthDemo.java:24)
package com.dineshonjava.mongo.test; import java.net.UnknownHostException; import com.mongodb.DB; import com.mongodb.DBCollection; import com.mongodb.Mongo; import com.mongodb.MongoException; /** * @author Dinesh Rajput * */ public class MongoAuthDemo { public static void main(String[] args) { try { Mongo mongo = new Mongo("localhost", 27017); DB db = mongo.getDB("dineshonjavaDB"); boolean auth = db.authenticate("dineshonjava", "password".toCharArray()); DBCollection collection = db.getCollection("empCollection"); if(auth){ System.out.println("TRUE"); }else{ System.out.println("FALSE"); } System.out.println("Done"); } catch (UnknownHostException e) { e.printStackTrace(); } catch (MongoException e) { e.printStackTrace(); } } }
Labels: mongodb