mongodb - 如何知道mongodb是否需要认证?

标签 mongodb mongodb-java

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

那么有没有办法知道数据库是否需要认证呢?

类似的东西:

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

最佳答案

刚遇到同样的问题,我是这样解决的:

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");
        }
    }
}

关于mongodb - 如何知道mongodb是否需要认证?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19885151/

相关文章:

ruby-on-rails - Papaerclip 不适用于更新方法

java - 使用 java 连接到远程 mongodb 服务器

mongodb - 使用 Java (Windows) 连接到在 Docker 中运行的 MongoDB 副本集

javascript - 如果子文档值不存在,Mongodb 将插入到子文档中

mysql - 使用子组构建组织

mongodb - 转储远程数据库 : Failed: error connecting to db server: no reachable servers

java - 我如何将结果写入文件

java - RabbitMQ (Java) 多消费者性能问题

java - 使用 jongo 将 JAVA 对象与 MongoDB 文档映射

javascript - 如何使用 mongoose 将对象数组保存在 mongodb 中?