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();
}
}
}
Awesome is the word for this link and for this tutorial.
I appreciate that.
Thanks a lot 🙂
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 .
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/
maven mongo-java-driver version ??
version???
Hello. Can I implement this example with JSF? And What I need to introduce?
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
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
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.
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);
}
For Beginners, I added this to check the wrong authentication. 😀
Thanks for your inputs.
How, we can build “App” bean in Spring? Want to do same stuff, but within Spring container.
Thanks
Another useful link i found Mongodb java utility