In this article, we will see how to make a secured LDAP authentication using Java.
First thing to do is importing the trust certificate to Java keystore. The default java keystore is named cacerts and is located in $JAVA_HOME/jre/lib/security/cacerts.
$JAVA_HOME is where your JDK is installed (By default : C:/Program Files/Java/jdk1.7.0_79/).
Table of contents
1- Register your SSL certificate into Java keystore
Java offers the certificate management utility keytool to handle certificates into your keystore. To import a certificate, you need to specify three arguments :
- -keystore : Absolute path to your keystore. (By default : C:\Program Files\Java\jdk1.7.0_79\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 :
1 |
keytool -keystore <PATH_TO_JRE>/lib/security/cacerts -import -alias certificate -file <PATH_TO_CERTIFICATE>/certificate.cer |
2- Running your application with SSL
To allow your application to connect over SSL you can choose one of the two solutions :
-
Writing code in your application
Add the following sytem properties before your LDAP authentication
1 2 3 4 5 6 |
//Path to your keystore where you registred the SSL certficate 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 :
1 |
-Djavax.net.ssl.keyStore="C:/Program Files/Java/jdk1.7.0_79/jre/lib/security/cacerts" -Djavax.net.ssl.keyStorePassword=changeit |
3- 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 :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
// 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 !"); e.printStackTrace(); } |