gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 10:44:05 26 4
gpt4 key购买 nike

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

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com