Reputation: 101
I think this question might be already answered some where but I am not able to find any solution so far. My issue was, I want to connect to LDAP and find a user from the ldap directory but the problem here is, it is a secure LDAP, so I have to authenticate with the ldap server that I am who I am by a certificate. So, I have installed that certificate using the following command
keytool -importcert -file D:\KSTLMRADD01.dev.chartercom.com.cer -keystore cacerts -alias KSTLMRADD01.dev.chartercom.com.cer
so by using system.setproperty I am setting the javax.net.ssl.truststore location and keystore password, since I have around 100 certificates in java keystore it was unable to use the appropriate certificate while making the connection, please see the below code and if there is any mistake or suggestions please let me know. Any help would be really great full.
public class TestLdap{
public static void main(String[] args){
System.setProperty("javax.net.ssl.trustStore", "C:\\Program Files\\Java\\jdk1.8.0_152\\jre\\lib\\security\\cacerts");
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
try {
// use the service user to authenticate
Hashtable<String, Object> serviceEnv = new Hashtable<String, Object>();
serviceEnv.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
serviceEnv.put(Context.PROVIDER_URL, ldapUrl);
serviceEnv.put(Context.SECURITY_AUTHENTICATION, "simple");
serviceEnv.put(Context.SECURITY_PROTOCOL, "ssl");
serviceEnv.put(Context.SECURITY_PRINCIPAL, serviceUserDN);
serviceEnv.put(Context.SECURITY_CREDENTIALS, serviceUserPassword);
LdapContext ctx = new InitialLdapContext(environment, null);
ctx.setRequestControls(null);
DirContect context = new InitialDirContext(environment);NamingEnumeration<?> namingEnum = ctx.search("ou=service_accounts,dc=com", "(objectclass=user)", getSimpleSearchControls());
while (namingEnum.hasMore ()) {
SearchResult result = (SearchResult) namingEnum.next ();
Attributes attrs = result.getAttributes ();
System.out.println(attrs.get("sn"));
}
namingEnum.close();
ctx.close();
}}
So I tried the DirContext and LdapContext but both are not working for me.
Upvotes: 2
Views: 3955
Reputation: 101
By setting the below two lines in my code I am able to trust those certificates.
System.setProperty("javax.net.ssl.trustStore", "C:\\Program Files\\Java\\jdk1.8.0_152\\jre\\lib\\security\\cacerts");
System.setProperty("javax.net.ssl.trustStorePassword", "changeit");
Upvotes: 2