Simple authentication involves sending a user name and password to the directory server. To avoid sending the user name and password in the clear, you can use SSL or Start TLS.
For both SSL and Start TLS, you pass LDAP options to the connection factory in order to set an SSL context, and set whether to use Start TLS. The SSL context lets you set a trust manager to check server certificates, and also set a key manager to provide keys when the server needs to check your client certificates. In the simplest, not-so-secure case, you can set up a trust manager that trusts all certificates.
The following example is an excerpt from the OpenDJ LDAP SDK example,
org.forgerock.opendj.examples.SimpleAuth.java
.
private static LDAPOptions getTrustAllOptions() throws GeneralSecurityException { LDAPOptions lo = new LDAPOptions(); SSLContext sslContext = new SSLContextBuilder() .setTrustManager(TrustManagers.trustAll()).getSSLContext(); lo.setSSLContext(sslContext); lo.setUseStartTLS(useStartTLS); return lo; }
A more secure and extensive SSL context would include a trust manager using a trust store and trust manager methods to check server certificates. If you also want to be able to authenticate to the server using your client certificate, you would need a key manager.
The authentication over SSL or using Start TLS in the trust-all case is
much like simple authentication over LDAP without connection-level security.
The primary differences are that you pass the LDAPOptions
to the LDAP connection factory, and that you handle the potential security
exception involved in setting up the SSL context.
/** * Perform authentication over a secure connection, trusting all server * certificates. */ private static void trustAllConnect() { Connection connection = null; try { final LDAPConnectionFactory factory = new LDAPConnectionFactory(host, port, getTrustAllOptions()); connection = factory.getConnection(); connection.bind(bindDN, bindPassword.toCharArray()); System.out.println("Authenticated as " + bindDN + "."); } catch (final ErrorResultException e) { System.err.println(e.getMessage()); System.exit(e.getResult().getResultCode().intValue()); return; } catch (final GeneralSecurityException e) { System.err.println(e.getMessage()); System.exit(ResultCode.CLIENT_SIDE_CONNECT_ERROR.intValue()); } finally { if (connection != null) connection.close(); } }
For a complete example in context, see SimpleAuth.java, one of the OpenDJ LDAP SDK examples.