Reputation: 7880
When you try to authenticate the user against a database, if the mongod is not started with the --auth parameter I get the error: Authentication failed!
So is there a way to know if the database needs authentication?
Something like that:
DB db = moClient.getDB(moClientURI.getDatabase());
if (db.needsAuthentication()){
db.authenticate(username, password.toCharArray());
if (db.isAuthenticated()){
//do something
} else {} // authentication failed
}
Upvotes: 3
Views: 2257
Reputation: 2262
Just got the same problem and this is the way I solved it:
private void authenticateMongo(String username, String password) throws IOException, AuthenticationException
{
DB db = mongoClient.getDB("admin");
if (username.equals("") && password.equals(""))
{
//As no user name and password was supplied, we consider that authentication is disabled
//But now we need to validate if it's really without authentication
try
{
mongoClient.getDatabaseNames();
}
catch(Exception e)
{
throw new AuthenticationException("Login or password is invalid");
}
}
else
{
boolean authenticationOK = db.authenticate(username, password.toCharArray());
if (!authenticationOK)
{
throw new AuthenticationException("Login or password is invalid");
}
}
}
Upvotes: 1