Plirkee Plirkee - 1 month ago 11
Java Question

A way to define / implement failover ldap servers in java code

I have the following code for Ldap user authentication:

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

}


There is one main drawback - it works only for one Ldap server.

Now I would like to define alternative Ldap servers for fail-over purposes (e.g. when the main ldap is down or is not accessible - the program should try to query the secondary ldap, if that is not available next one etc.).

How would I achieve that?

And how would I minimise authentication time if the primary server would stay offline for a long time?

Thanks in advance.

Answer

Just add multiple LDAP PROVIDER_URLs:

// Specify list of [space-separated URL][1]s
env.put(Context.PROVIDER_URL, 
    "ldap://ourLdapServer " +
    "ldap://ourLdapServer2 " + 
    "ldap://ourLdapServer3 " +
    "ldap://ourLdapServer4");