The following example demonstrates how to make connection to a LDAP server using JNDI (Java Naming and Directory Interface) APIs in Java. The JNDI’s interfaces, classes and exceptions are available in the javax.naming.* and javax.naming.directory.* packages which come with JDK. That means you don’t have to use any external libraries for working with LDAP servers, in most cases.

First, you need to specify URL of the LDAP server in the following form:

String url = "ldap://localhost:389";
That specifies URL of a LDAP server which is running on local host and is listening on the default port number 389 - a well known port number of the Lightweight Directory Access Protocol.

Second, we need to specify some environment properties for the connection and authentication in a Hashtable object, as shown in the following code snippet:

Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, url);
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
env.put(Context.SECURITY_CREDENTIALS, "secret");
Here, five environment properties are:

  • INITIAL_CONTEXT_FACTORY: specifies the fully qualified class name of the factory class that will create an initial context, default is com.sun.jndi.ldap.LdapCtxFactory.
  • PROVIDER_URL: specifies URL of the service provider to use, e.g. “ldap://hostname:389”.
  • SECURITY_AUTHENTICATION: specifies the authentication mechanism to use, which is one of the following strings:
    • none”: use no authentication (anonymous).
    • simple”: use weak authentication (password in clear text).
    • sasl_mech: use strong authentication with SASL (Simple Authentication and Security Layer).
  • SECURITY_PRINCIPAL: specifies username of the principal for the authentication, in the form of a LDAP distinguished name, e.g. “uid=admin,ou=system”.
  • SECURITY_CREDENTIALS: specifies password of the principal for the authentication.
Finally, pass the Hashtable of environment properties when creating a new context like this:

DirContext ctx = new InitialDirContext(env);
If there is no exceptions occurred, the connection is made and the caller is authenticated. Then you can perform further operations like searching for objects in the directory. Here’s the complete example code:

String url = "ldap://localhost:10389";
Hashtable env = new Hashtable();
env.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, url);
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, "uid=admin,ou=system");
env.put(Context.SECURITY_CREDENTIALS, "secret");

try {
	DirContext ctx = new InitialDirContext(env);
	System.out.println("connected");
	System.out.println(ctx.getEnvironment());
	
	// do something useful with the context...

	ctx.close();

} catch (AuthenticationNotSupportedException ex) {
	System.out.println("The authentication is not supported by the server");
} catch (AuthenticationException ex) {
	System.out.println("incorrect password or username");
} catch (NamingException ex) {
	System.out.println("error when trying to create the context");
}
The above code tries to connect to a local LDAP server (here, we tested with Apache DS server which is listening on its default port number 10389), print “connected” and environment properties to the console. Here’s the output:

connected
{java.naming.provider.url=ldap://localhost:20389, java.naming.factory.initial
=com.sun.jndi.ldap.LdapCtxFactory,java.naming.security.principal=uid=admin,ou=system,
java.naming.security.authentication=simple, java.naming.security.credentials=secret}
Note that when attempting to connect to a LDAP server, three exceptions might be thrown:

  • AuthenticationNotSupportedException: if the specified authentication mechanism is not supported by the server.
  • AuthenticationException: if either the username or password is incorrect.
  • NamingException: if a naming exception is encountered.


References:

 

Other Java Coding Tutorials:


About the Author:

is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.



Attachments:
Download this file (LDAPAuthenticationExample.zip)LDAPAuthenticationExample.zip[Java source file]3 kB

Add comment

   


Comments 

#7Reddy2024-01-27 06:45
Hi, I am able to connect, but context search is not working. please help me with example code.
Quote
#6Kamran2021-11-02 06:27
Looking for similar C# code. iam able to connect my ldap directory from above code
Quote
#5harsh2020-04-13 05:02
hi i am getting naming exception what does it mean and how to resolve it? it is showing connection timeout
Quote
#4Prateek2019-03-28 05:20
I'm learning LDAP using java using simple java ee, I'm stuck on the thing that I want the current user login username has to be checked by LDAP in active directory.
Quote
#3Kristin2016-03-31 03:44
Very good. It helps me a lot. It solve my problem which I have been dying to figure out for these past two days. Thanks again.
Quote