Elegant Java LDAP Disable

Currently, from java, I am connecting to LDAP with the following code, a very typical example:

    Hashtable<String, String> env = new Hashtable<String, String>();

    env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, url);
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, user);
    env.put(Context.SECURITY_CREDENTIALS, password);

    LdapContext ctx = null;

    try
    {
        ctx = new InitialLdapContext(env, null);
        return true;
    }
    catch (NamingException ex)
    {
        return false;
    }
    finally
    {
        if (ctx != null)
        {
            try {
                ctx.close();
            } catch (NamingException e) {
                log.warn(e.getMessage());
            }
        }
    }

This works in terms of user authentication. However, the LDAP administrator tells me that I am not disconnecting gracefully when the binding failed. Error on the LDAP side (for example):

[24 / January / 2013: 13: 20: 44 -0500] conn = 249 op = -1 msgId = -1 - close from [ipaddress]: 44724 - A1 - The client disconnected -

He also says that when this is a successful authentication, disconnecting is elegant. I think this is because I am doing ctx.close()in this situation.

However, when authentication fails, an exception is actually thrown from the string new InitialLdapContext(env, null). Therefore, no context is returned, and no call is made in any context.

- , , , ?

+5
3

? , : , . , , . JNDI LDAP , , , , . JNDI LDAP-. . - , , .

+3

LDAP

NamingEnumeration<SearchResult> results

():

} finally {
            if(results != null) {
                try {
                    results.close();
                } catch (NamingException e) {
                    LOG.error("Error closing LDAP results", e);
                }
            }
+2

Create a context object before adding any authentication data. Then use addToEnvironment to add the credentials. Finally, do a very simple search (my approach is to look for the differName username attribute). The search will fail if the credentials are not good, and you should still close the context object.

An added bonus to this approach is that you can maintain a pool of context objects and avoid constantly connecting / disconnecting for authentication.

Hashtable<String,String> environment = new Hashtable<String,String>();
environment.put("java.naming.provider.url", url);
environment.put("java.naming.factory.initial", "com.sun.jndi.ldap.LdapCtxFactory");

InitialLdapContext context = new InitialLdapContext(environment, null);

...

context.addToEnvironment("java.naming.security.principal", principal);
context.addToEnvironment("java.naming.security.credentials", credentials);

...

// execute some kind of search, based on your needs
0
source

All Articles