'Ldap ssl with dynamic truststore

I am trying to connect to a ldap over ssl. I have generated a .jks file with the certificate entry. I do not want to import this to cacerts rather want to access it dynamically when i initialize the ldap connection.

if (sslAuth) {
        ldapHost = "ldaps://" + ldapHost;
    } else {
        ldapHost = "ldap://" + ldapHost;
    }
    Hashtable<Object, Object> env = new Hashtable<Object, Object>();
    env.put(Context.INITIAL_CONTEXT_FACTORY,
            "com.sun.jndi.ldap.LdapCtxFactory");
    env.put(Context.PROVIDER_URL, ldapHost);    
    env.put(Context.SECURITY_AUTHENTICATION, "simple");
    env.put(Context.SECURITY_PRINCIPAL, "userName");
    env.put(Context.SECURITY_CREDENTIALS, "password");      
    if (sslAuth) {
        System.setProperty("javax.net.ssl.trustStore", "C:\\temp\\AD-Cert-TrustStore.jks");
        System.setProperty("javax.net.ssl.trustStorePassword", "changeit");     
        env.put(DirContext.SECURITY_PROTOCOL, "ssl");
    }
    LdapContext ctx = new InitialLdapContext(env, null);
    return ctx;

But i am getting the below exception

 javax.naming.CommunicationException: simple bind failed: ldaphost: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]


Solution 1:[1]

If all the necessary javax.net....-properties are correctly spelled and have correct values, there must be premature initialization of some ssl-aware objects. For example, if in your app SslRMIClientSocketFactory or SslRMIServerSocketFactory are created before setting those properties, then subsequent attempts to start ssl-connection even with new factories will behave as if the properties were not set.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 user4751294