LDAP Authentication using SSL

Add your SSL certificate into Java keystore

Java support the certificate management utility keytool to handle certificates into your keystore.For import a certificate, you need to specify three arguments :

keystore : Absolute path to your keystore. (By default : C:\Program Files\Java\jdk1.8.0_232\jre\lib\security)
alias : Give a name to your certificate The given name should not already exist in the keystore
file : Absolute path to the certificate you want to import

Use the following code to import your certificate into the default java keystore :

keytool -keystore <PATH_TO_JRE>/lib/security/cacerts -import -alias certificate -file <PATH_TO_CERTIFICATE>/certificate.cer

The default keystore password is : changeit

Running your application with SSL

To allow your application to connect with SSL you can choose one of the two solutions :

Writing code in your application code
Add the following system properties before LDAP authentication

//Path to your keystore where you registered the SSL certificate
String keystorePath = "C:/Program Files/Java/jdk1.7.0_79/jre/lib/security/cacerts";
System.setProperty("javax.net.ssl.keyStore", keystorePath);
// Password of your java keystore. Default value is : changeit
System.setProperty("javax.net.ssl.keyStorePassword", "changeit");

Add JVM arguments
Start your application by adding the folowing arguments :

-Djavax.net.ssl.keyStore="C:/Program Files/Java/jdk1.8.0_232/jre/lib/security/cacerts" -Djavax.net.ssl.keyStorePassword=changeit

LDAP Connection

Once you added the trusted certificate to Java keystore and started your application with the required arguments, you can use the following code to make a LDAP authentication :

// Setting the LDAP connection information
Hashtable<String, String> env = new Hashtable<String, String>();
env.put(Context.PROVIDER_URL, "ldaps://server.local:636");
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "cn=radouane,ou=people,o=RoufidTutorials,c=fr");
env.put(Context.SECURITY_CREDENTIALS, "password");
DirContext ctx = null;
try {
	// Openning the connection
	ctx = new InitialDirContext(env);
	// Use your context here...
} catch (NamingException e) {
	System.out.println("Problem occurs during context initialization !");

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.