我有以下用于 Ldap 用户身份验证的代码:
import java.util.Hashtable;
import javax.naming.*;
import javax.naming.directory.Attributes;
import javax.naming.directory.SearchControls;
import javax.naming.directory.SearchResult;
import javax.naming.ldap.InitialLdapContext;
import javax.naming.ldap.LdapContext;
public class LdapUtil {
public static final String PROVIDER_URL= "ldap://ourLdapServer";
public static final String SECURITY_AUTHENTICATION="simple";
public static final String SECURITY_PRINCIPAL_POSTFIX="@org.local";
private String ldapAttributes[] = null;
public boolean isCorrectUser(String user, String pass){
boolean result = false;
if (user == null || pass == null || "".equals(user) || "".equals(pass)) {
return result;
}
try {
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, PROVIDER_URL);
env.put(Context.SECURITY_AUTHENTICATION, SECURITY_AUTHENTICATION);
env.put(Context.SECURITY_PRINCIPAL, user + SECURITY_PRINCIPAL_POSTFIX);
env.put(Context.SECURITY_CREDENTIALS, pass);
LdapContext ctxGC = new InitialLdapContext(env, null);
ldapAttributes = getUserBasicAttributes(user,ctxGC);
ctxGC.close();
result = true;
//System.out.println("LDAP authentication for " + username + " succeeded!");
} catch (Exception e) {
// Not authenticated
result = false;
//System.out.println("LDAP authentication for " + username + " failed!");
}
return result;
}
}
有一个主要缺点 - 它仅适用于一个 Ldap 服务器。
现在我想定义备用 Ldap 服务器用于故障转移目的(例如,当主 ldap 关闭或不可访问时 - 程序应尝试查询辅助 ldap,如果下一个不可用等) .
我将如何实现?
如果主服务器长时间处于离线状态,我将如何最大程度地减少身份验证时间?
提前致谢。
最佳答案
只需添加多个 LDAP PROVIDER_URL:
// Specify list of [space-separated URL][1]s
env.put(Context.PROVIDER_URL,
"ldap://ourLdapServer " +
"ldap://ourLdapServer2 " +
"ldap://ourLdapServer3 " +
"ldap://ourLdapServer4");
关于java - 一种在 java 代码中定义/实现故障转移 ldap 服务器的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40218516/