title: how to accept self-signed certificates for JNDI/LDAP connections?
body: <p>I need to connect to an LDAP directory over SSL.</p>
  
  <p>In non-production environments, we use self-signed certificates which, of course, fails to validate with:</p>
  
  <pre><code>javax.naming.CommunicationException: simple bind failed: ldapserver:636 [Root exception is javax.net.ssl.SSLHandshakeException: sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target]
   at com.sun.jndi.ldap.LdapClient.authenticate(LdapClient.java:197)
   at com.sun.jndi.ldap.LdapCtx.connect(LdapCtx.java:2694)
   at com.sun.jndi.ldap.LdapCtx.&lt;init&gt;(LdapCtx.java:293)
   at com.sun.jndi.ldap.LdapCtxFactory.getUsingURL(LdapCtxFactory.java:175)
   at com.sun.jndi.ldap.LdapCtxFactory.getUsingURLs(LdapCtxFactory.java:193)
   at com.sun.jndi.ldap.LdapCtxFactory.getLdapCtxInstance(LdapCtxFactory.java:136)
   at com.sun.jndi.ldap.LdapCtxFactory.getInitialContext(LdapCtxFactory.java:66)
   at javax.naming.spi.NamingManager.getInitialContext(NamingManager.java:667)
   at javax.naming.InitialContext.getDefaultInitCtx(InitialContext.java:288)
   at javax.naming.InitialContext.init(InitialContext.java:223)
   at javax.naming.ldap.InitialLdapContext.&lt;init&gt;(InitialLdapContext.java:134)
  </code></pre>
  
  <p>I am aware of how to use a <a href="https://stackoverflow.com/questions/859111/how-do-i-accept-a-self-signed-certificate-with-a-java-httpsurlconnection">custom trust manager for SSL-enabled connections</a>, but don't know how to use one in connection with the JNDI API where I don't manage the actual connection. That is, where is the following standard setup will I be able to plug the trust manager?</p>
  
  <p>Thanks in advance.</p>
  
  <pre><code>Hashtable env = new Hashtable();
  env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
  env.put(Context.PROVIDER_URL, "ldaps://ldapserver:636");
  env.put(Context.SECURITY_PROTOCOL, "ssl");
  env.put(Context.SECURITY_AUTHENTICATION, "simple");
  env.put(Context.SECURITY_PRINCIPAL, "myUser");
  env.put(Context.SECURITY_CREDENTIALS, "myPassword");
  LdapContext ctx = new InitialLdapContext(env, null);
  ctx.search (...)
  </code></pre>