LDAP authentication in Java
In this tutorial, we share the common code block that is used to connect to an LDAP server in Java.
1. InitialDirContext
To connect to an LDAP server, you can use the InitialDirContext class provided by the JDK.
You can use the following block anytime you need to connect to an LDAP server:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | private void connectToLDAP() { try { Properties props = new Properties(); props.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory"); props.put(Context.PROVIDER_URL, "ldap://ldap.forumsys.com:389"); props.put(Context.SECURITY_PRINCIPAL, "uid=riemann,dc=example,dc=com"); props.put(Context.SECURITY_CREDENTIALS, "password"); InitialDirContext context = new InitialDirContext(props); System.out.println("Succesfully connected to LDAP server"); } catch (Exception e) { System.out.println("Couldn't connect to LDAP server"); e.printStackTrace(); } } |