DATADOC-51 - Enabling security on MongoTemplate results in the driver throwing "java.lang.IllegalStateException: can't call authenticate twice on the same DBObject"

This commit is contained in:
Mark Pollack
2011-04-09 12:44:10 -04:00
parent dac4aed120
commit 357818c716
2 changed files with 35 additions and 4 deletions

View File

@@ -19,13 +19,39 @@ import org.springframework.dao.DataAccessResourceFailureException;
public class CannotGetMongoDbConnectionException extends DataAccessResourceFailureException {
private String username;
private char[] password;
private String database;
private static final long serialVersionUID = 1172099106475265589L;
public CannotGetMongoDbConnectionException(String msg, Throwable cause) {
super(msg, cause);
}
public CannotGetMongoDbConnectionException(String msg) {
super(msg);
}
public CannotGetMongoDbConnectionException(String msg, String database, String username, char[] password2) {
super(msg);
this.username = username;
this.password = password2;
this.database = database;
}
public String getUsername() {
return username;
}
public char[] getPassword() {
return password;
}
public String getDatabase() {
return database;
}
}

View File

@@ -16,6 +16,7 @@
package org.springframework.data.document.mongodb;
import com.mongodb.CommandResult;
import com.mongodb.DB;
import com.mongodb.Mongo;
import org.apache.commons.logging.Log;
@@ -92,10 +93,14 @@ public abstract class MongoDbUtils {
LOGGER.trace("Getting Mongo Database name=["+databaseName+"]");
DB db = mongo.getDB(databaseName);
boolean credentialsGiven = username != null && password != null;
if (credentialsGiven && !db.authenticate(username, password)) {
throw new CannotGetMongoDbConnectionException("Failed to authenticate with Mongo using the given credentials");
if (credentialsGiven && !db.isAuthenticated()) {
//Note, can only authenticate once against the same com.mongodb.DB object.
if (!db.authenticate(username, password)) {
throw new CannotGetMongoDbConnectionException("Failed to authenticate to database [" + databaseName +
"], username = [" + username + "], password = [" + new String(password) + "]", databaseName, username, password );
}
}
// Use same Session for further Mongo actions within the transaction.