Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I need to use multiple LDAP provider. How can I check LDAP server availability?

We have multiple LDAP/domain servers.(ex. LDAP://server1.com:389/DC=server1,DC=COM, LDAP://server2.com:389/DC=server2,DC=COM) I need to use one of them by checking availabilty.

try {
    Hashtable<String, String> env = new Hashtable<String, String>();
    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, "LDAP://server1.com:389/DC=server1,DC=COM");
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, username);
    env.put(Context.SECURITY_CREDENTIALS, password);

    DirContext ctx = new InitialDirContext(env);
} catch(NamingException ex) {
}
like image 283
nikli Avatar asked Dec 27 '22 11:12

nikli


1 Answers

You can just use multiple ldap server URLs in the PROVIDER_URL environment property like this:

Hashtable env = new Hashtable(11);
env.put(Context.INITIAL_CONTEXT_FACTORY, 
    "com.sun.jndi.ldap.LdapCtxFactory");

// Specify list of space-separated URLs
env.put(Context.PROVIDER_URL, 
    "ldap://notthere:389/o=JNDITutorial " +
    "ldap://localhost:389/o=JNDITutorial " + 
    "ldap://remotehost/o=JNDITutorial " +
    "ldap://thirdhost:389/o=JNDITutorial");

// Create initial context
DirContext ctx = new InitialDirContext(env);

// See which server was used
System.out.println(ctx.getEnvironment().get(Context.PROVIDER_URL));

// do something useful with ctx
....

Whichever URL is successful, that will be used in the context

like image 103
da-vinci-code Avatar answered Feb 25 '23 01:02

da-vinci-code