当您尝试根据数据库对用户进行身份验证时,如果 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/