MongoDB Authentication failure from mongo java client - java

I tried to connect to mongo db version 3.2 using mongo java client version 3.2 and getting the following exception, any idea what went wrong here?
com.mongodb.MongoSecurityException: Exception authenticating
at com.mongodb.connection.NativeAuthenticator.authenticate(NativeAuthenticator.java:48)
at com.mongodb.connection.InternalStreamConnectionInitializer.authenticateAll(InternalStreamConnectionInitializer.java:99)
at com.mongodb.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:44)
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115)
at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:128)
at java.lang.Thread.run(Thread.java:745)
Caused by: com.mongodb.MongoCommandException: Command failed with error 18: 'auth failed' on server 10.100.5.41:27017. The full response is { "ok" : 0.0, "errmsg" : "auth failed", "code" : 18 }
at com.mongodb.connection.CommandHelper.createCommandFailureException(CommandHelper.java:170)
at com.mongodb.connection.CommandHelper.receiveCommandResult(CommandHelper.java:123)
at com.mongodb.connection.CommandHelper.executeCommand(CommandHelper.java:32)
at com.mongodb.connection.NativeAuthenticator.authenticate(NativeAuthenticator.java:46)
... 5 more
Following is the code I used to connect.
MongoClient mongoClient = null;
try {
MongoCredential credential = MongoCredential.createMongoCRCredential("admin", "mydatabase", "admin123".toCharArray());
mongoClient = new MongoClient(new ServerAddress("10.100.5.41", 27017), Arrays.asList(credential));
MongoDatabase database = mongoClient.getDatabase("mydatabase");
System.out.println(database.getName());
MongoCollection collection = database.getCollection("user");
MongoCursor cursor = collection.find().iterator();
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
} catch (Exception e) {
e.printStackTrace();
}

After hours of debugging, db administrator told that, he has changed the username and password. At times I wonder why I become a Software Engineer.

Related

JAVA com.mongodb.MongoQueryException: Query failed with error code 13 and error message 'command find requires authentication'

com.mongodb.MongoQueryException: Query failed with error code 13 and
error message 'command find requires authentication'
How to create a mongo client using a password in java.
I know there was method like this:
public MongoClient(final ServerAddress addr, final List<MongoCredential> credentialsList);
But it is shown as deprecated, there is another method which requires MongoClientOptions:
public MongoClient(final ServerAddress addr, final MongoCredential credential, final MongoClientOptions options)
But I do not have any options to send. So, is there any way I can create mongo client in java using a password?
For the find command to execute, you need to authenticate with mongo first.
An example of how you may be doing authentication:
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!");
}
This should work fine for you.
You can check the example code in this article: https://www.mkyong.com/mongodb/java-authentication-access-to-mongodb/
When using the mongo-java-driver the following would be appropriate:
- note this is not using the deprecated method anymore, but setting the writeconcern to Journaled (which is recommended)
String username = "test";
String database = "something";
String password = "secret";
MongoCredential mongoCredential = MongoCredential.createCredential(username, database, password.toCharArray());
MongoClientOptions options = MongoClientOptions.builder()
.writeConcern(WriteConcern.JOURNALED).build();
MongoClient mongoClient = new MongoClient(new ServerAddress("host1", 27017), Arrays.asList(mongoCredential), options);

com.mongodb.MongoTimeoutException: Timed out after 10000 ms while waiting to connect

I assumed this question was asked several times but I had to reask it again. Because solutions provided for this question did not give me an exact answer to get rid of this bloody error.
I use mongo-java-driver-2.12.4 and mongo.jar when I try to insert document to db I get following error. Any help is appreciated.
Error :
Exception in thread "main" com.mongodb.MongoTimeoutException: Timed out after 10000 ms while waiting to connect. Client view of cluster state is {type=Unknown, servers=[{address=127.0.0.1:27000, type=Unknown, state=Connecting, exception={com.mongodb.MongoException$Network: Exception opening the socket}, caused by {java.net.ConnectException: Connection refused: connect}}, {address=127.0.0.1:27001, type=Unknown, state=Connecting, exception={com.mongodb.MongoException$Network: Exception opening the socket}, caused by {java.net.ConnectException: Connection refused: connect}}, {address=127.0.0.1:27002, type=Unknown, state=Connecting, exception={com.mongodb.MongoException$Network: Exception opening the socket}, caused by {java.net.ConnectException: Connection refused: connect}}]
at com.mongodb.BaseCluster.getDescription(BaseCluster.java:128)
Code :
public class MongoDbConnectDatabase {
public static void main(String[] args) {
// To connect to mongodb server
try {
List<ServerAddress> lstServer = new ArrayList<ServerAddress>();
lstServer.add(new ServerAddress("127.0.0.1", 27000));
lstServer.add(new ServerAddress("127.0.0.1", 27002));
lstServer.add(new ServerAddress("127.0.0.1", 27001));
MongoClient mongoClient = new MongoClient(lstServer);
// Now connect to your database
DB db = mongoClient.getDB("test");
System.out.println("connect to database successfully");
DBCollection coll = db.createCollection("mycol", null);
System.out.println("Collection created successfully");
DBCollection colReceived= db.getCollection("mycol");
System.out.println("Collection mycol selected successfully");
BasicDBObject doc = new BasicDBObject("title", "MongoDB").
append("description", "database").
append("likes", 100).
append("url", "http://www.tutorialspoint.com/mongodb/").
append("by", "tutorials point");
colReceived.insert(doc);
System.out.println("Document inserted successfully");
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
You obtain a Connection refused. Are you sure mongod is running?
Try to connect with mongoclient:
mongo 127.0.0.1:27000/test
and this for all the three instances (27000, 27002, 27001).
If you have problem also with mongoclient, check your logs.
another reason for this error can be that the version of mongo-java-driver is not compatible with your mongo application. My case : I was using mongo-java-driver version 2.12.3 with mongo 3.0.8 -> doesn't work. (https://docs.mongodb.com/ecosystem/drivers/driver-compatibility-reference/#reference-compatibility-mongodb-java)
Here is all the possible reason for this error are listed. In my case it was due to replicaset not initialised. Initialise replicaset using rs.initiate().
In my case I used the volume created from production data and used it in staging. Since the local db was having old replicaset config, it was not able to become PRIMARY. I did the following thing to make it PRIMARY:
>use local
> db.dropDatabase();
{ "dropped" : "local", "ok" : 1 }
> rs.initiate()
>myrepl:PRMIARY
Now the client was able to connect and perform read/write operations.
Giving a snippet that might give a basic idea.
package com.mkyong.core;
import java.net.UnknownHostException;
import com.mongodb.BasicDBObject;
import com.mongodb.DB;
import com.mongodb.DBCollection;
import com.mongodb.DBCursor;
import com.mongodb.MongoClient;
public class MongoTest {
static DBCollection table;
public static void main(String[] args) {
MongoClient mongo = null;
try {
mongo = new MongoClient("localhost", 27017);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DB db = mongo.getDB("lending");
table = db.getCollection("bureaudata");
/**** Find and display ****/
BasicDBObject searchQuery = new BasicDBObject();
searchQuery.put("id", "63057298");
DBCursor cursor = table.find(searchQuery);
while (cursor.hasNext()) {
System.out.println(cursor.next());
}
}
}

Connection to MongoDB 2.6.3 using 3.0.0 driver from Java (eclipse)

My simple program to connect to mongodb 2.6.3 using 3.0.0 driver fails with
"Command failed with error 59: 'no such cmd: saslStart' on server ...."
Any insight is much appreciated.
public static void main(String[] args) {
MongoCredential credential = MongoCredential.createCredential(MY_TEST_DATABASE_USER, MY_TEST_DATABASE, MY_TEST_DATABASE_PWD);
// MongoCredential credential = MongoCredential.createScramSha1Credential(MY_TEST_DATABASE_USER, MY_TEST_DATABASE, MY_TEST_DATABASE_PWD); // this failed as well
try (MongoClient mongoClient = new MongoClient(new ServerAddress(DB_SERVER_2_6_3, DB_PORT), Arrays.asList(credential))) {
MongoDatabase mdb = mongoClient.getDatabase(MY_TEST_DATABASE);
MongoCollection<Document> coll = mdb.getCollection(MY_TEST_COLLECTION);
if (coll != null) {
System.out.println(coll.find().first());
}
}
}
Figured out by trial and error. (disappointed with mongo online support/docs on this issue)
Used "admin" database when creating credentials. Figured this out by looking at the connection settings in my Robomongo client.
MongoCredential credential = MongoCredential.createCredential(MY_TEST_DATABASE_USER, "admin", MY_TEST_DATABASE_PWD);

Mongo Timeout Exception

I've been searching for hours, and I can't find out why this isn't working, could you give me a hand guys? I'm trying to implement mongodb on my project, it seems to connect all right, but when I try to modify/access something on it, it gives me this "Mongo Timeout Exception".
try {
MongoCredential credential = MongoCredential.createCredential(USER, DATABASE, PASSWORD.toCharArray());
MongoClient mongoClient = new MongoClient(new ServerAddress(HOST), Arrays.asList(credential));
DB database = mongoClient.getDB(DATABASE);
DBCollection collection = database.getCollection(COLLECTION);
DBCursor cursor = collection.find();
cursor.next();
System.out.println("Success!");
} catch(Exception ex) { ex.printStackTrace(); }
com.mongodb.MongoTimeoutException: Timed out after 10000 ms while waiting to connect. Client view of cluster state is {type=Unknown, servers=[{address=104.236.68.242:27017, type=Unknown, state=Connecting}]
at com.mongodb.BaseCluster.getDescription(BaseCluster.java:128)
at com.mongodb.DBTCPConnector.getClusterDescription(DBTCPConnector.java:394)
at com.mongodb.DBTCPConnector.getType(DBTCPConnector.java:571)
at com.mongodb.DBTCPConnector.isMongosConnection(DBTCPConnector.java:368)
at com.mongodb.Mongo.isMongosConnection(Mongo.java:622)
at com.mongodb.DBCursor._check(DBCursor.java:494)
at com.mongodb.DBCursor._next(DBCursor.java:551)
at com.mongodb.DBCursor.next(DBCursor.java:701)
at net.Heiden.DB.Testing.main(Testing.java:29)
Any Help is apreciated.
Thanks ^^

MongoDB and Java

I'm trying to use MongoDB in a Java Web Service.
As suggested in Mongo tutorial I should have a MongoClient, let it be dbInstance, connection pool and call dbinstance to get a connection to the database, which is in localhost.
So this is what I have:
private static MongoClient dbInstance = null;
public static DB getDBInstance() {
if (dbInstance == null) {
try {
dbInstance = new MongoClient();
registerShutdownHook();
}
catch (Exception exc) {
System.out.println("Exception");
}
}
return dbInstance.getDB("SAED");
}
What I don't understand is how I can understand if I'm connected to the DB, because, also il mongo isn't working (by starting mongod service) it doesn't throw exceptions.
And another question, I have multiple thread calling Class.getDBInstance, should I synchronize it, and if yes, how can I do that?
You will be thrown an exception when the mongo is not running while you try to connect.
When you do the MongoClient(), it will always look for in the localhost for port 27017 to connect. You can also parameterize this to connect to a different machine and/or port.
You can read more in depth details about this at Mongo Documentation.
MongoClient mongoClient = new MongoClient();
// or
MongoClient mongoClient = new MongoClient( "localhost" );
// or
MongoClient mongoClient = new MongoClient( "localhost" , 27017 );
Regarding your synchronization question,
Yes, you can synchronize at a block level to make it better instead of at the method level.

Categories