Question

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                
        }
Was it helpful?

Solution

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");
        }
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top