如何知道mongodb是否需要身份验证?

时间:2013-11-10 01:13:11

标签: mongodb mongodb-java

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

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

类似的东西:

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

1 个答案:

答案 0 :(得分: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");
        }
    }
}
相关问题