2013-11-10 33 views
1

当您尝试根据数据库对用户进行身份验证时,如果mongod未使用--auth参数启动,则会出现以下错误:身份验证失败!如何知道mongodb是否需要验证?

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

类似的东西:

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

,但[这](HTTP:// docs.mongodb.org/ecosystem/tutorial/authenticate-with-java-driver)和[this](http://www.mkyong.com/mongodb/java-authentication-access-to-mongodb)示例可能会有帮助。 –

+0

不,已经检查过这些链接。它不会告诉你如何知道mongodb是否需要认证。当然,我可以运行一个命令并检查是否得到'认证失败',看看它是否需要授权,但这不是一个方便的方法。 –

+1

您可以通过db.serverCmdLineOpts()或db.adminCommand('getCmdLineOpts')启动服务器参数 –

回答

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

db.authenticate方法在较新的Java库中已被弃用 – jugglingcats

+0

匿名如何在除管理员之外的其他数据库上进行身份验证 –

+0

在这种情况下,你需要对所有的数据库执行上面的代码 –

相关问题