3

当您尝试针对数据库对用户进行身份验证时,如果 mongod 未使用 --auth 参数启动,我会收到错误:身份验证失败!

那么有没有办法知道数据库是否需要身份验证?

像这样的东西:

        DB db = moClient.getDB(moClientURI.getDatabase());                         
        if (db.needsAuthentication()){
            db.authenticate(username, password.toCharArray());
            if (db.isAuthenticated()){
            //do something                
            } else {} // authentication failed                
        }
4

1 回答 1

1

刚遇到同样的问题,这就是我解决它的方法:

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");
        }
    }
}
于 2013-12-12T11:47:10.310 回答