1. Introduction

In this article, we’ll cover how to authenticate a user with LDAP using pure Java. Furthermore, we’ll explore how to search for a user’s distinguished name (DN). This is important because LDAP requires the DN to authenticate the user.

To do the search and user authentication, we’ll use the directory service access capabilities of the Java Naming and Directory Interface (JNDI).

First, we’ll briefly discuss what LDAP and JNDI are. Then we’ll discuss how to authenticate with LDAP through the JNDI API.

2. What Is LDAP?

The Lightweight Directory Access Protocol (LDAP) defines a way for clients to send requests and receive responses from directory services. We call a directory service using this protocol an LDAP server.

The data served by an LDAP server is stored in an information model based on X.500. This is a group of computer networking standards for electronic directory services.

3. What Is JNDI?

JNDI provides a standard API for applications to discover and access naming and directory services. Its fundamental purpose is to provide a way for applications to access components and resources. This being, both locally and over a network.

Naming services underly this capability because they provide single-point access to services, data, or objects by name in a hierarchical namespace. The name given to each of these local or network-accessible resources is configured on the server hosting the naming service.

We can access directory services, like LDAP, by using the naming service interface of JNDI. This is because a directory service is merely a specialized type of naming service that enables each named entry to have a list of attributes associated with it.

Besides attributes, each directory entry may have one or more children. This enables entries to be linked hierarchically. In JNDI, children of directory entries are represented as subcontexts of their parent context.

A key benefit of the JNDI API is that it’s independent of any underlying service provider implementation, for example, LDAP. Therefore, we can use JNDI to access an LDAP directory service without needing to use protocol-specific APIs.

No external libraries are needed to use JNDI because it’s part of the Java SE platform. Further, being a core technology in Java EE, it is widely used to implement enterprise applications.

4. JNDI API Concepts to Authenticate with LDAP

Before discussing the example code, let’s cover some fundamentals about using the JNDI API for LDAP-based authentication.

To connect to an LDAP server, we first need to create a JNDI InitialDirContext object. When doing so, we need to pass environment properties into its constructor as a Hashtable to configure it.

Amongst others, we need to add properties to this Hashtable for the user name and password that we wish to authenticate with. To do so, we must set the user’s DN and his password to the Context.SECURITY_PRINCIPAL and Context.SECURITY_CREDENTIALS properties, respectively.

InitialDirContext implements DirContext, the main JNDI directory service interface. Through this interface, we can use our new context to perform various directory service operations on the LDAP server. These include binding names and attributes to objects and searching for directory entries.

It’s worth noting that the objects returned by JNDI will have the same names and attributes as their underlying LDAP entries. Thus, to search for an entry, we can use its name and attributes as criteria to look it up.

Once we have retrieved a directory entry through JNDI, we can look at its attributes using the Attributes interface. Further, we can use the Attribute interface to inspect each of them.

5. What If We Don’t Have the User’s DN?

Sometimes we don’t have the DN of the user immediately available to authenticate with. To get around this, we first need to create an InitialDirContext using administrator credentials. After that, we can use it to search for the relevant user from the directory server and get his DN.

Then once we have the user’s DN, we can authenticate him by creating a new InitialDirContext, this time with his credentials. To do this, we first need to set the user’s DN and password in the environment properties. After that, we need to pass these properties into the InitDirContext‘s constructor when creating it.

Now that we’ve discussed authenticating a user through LDAP using the JNDI API, let’s go through the example code.

6. Example Code

In our example, we’ll use the embedded version of the ApacheDS directory server. This is an LDAP server built using Java and designed to run in embedded mode within unit tests.

Let’s look at how to set it up.

6.1. Setting up the Embedded ApacheDS Server

To use the embedded ApacheDS server, we need to define the Maven dependency:

<dependency>
    <groupId>org.apache.directory.server</groupId>
    <artifactId>apacheds-test-framework</artifactId>
    <version>2.0.0.AM26</version>
    <scope>test</scope>
</dependency>

Next, we need to create a unit test class using JUnit 4. To use the embedded ApacheDS server in this class, we must declare that it extends AbstractLdapTestUnit from the ApacheDS library. As this library is not compatible with JUnit 5 yet, we need to use JUnit 4.

Additionally, we need to include Java annotations above our unit test class declaration to configure the server. We can see which values to give them from the full code example, which we will explore later.

Lastly, we’ll also need to add users.ldif to the classpath. This is so the ApacheDS server can load LDIF formatted directory entries from this file when we run our code example. When doing so, the server will load the entry for the user Joe Simms.

Next, we’ll discuss the example code that will authenticate the user. To run it against the LDAP server, we’ll need to add our code to a method in our unit test class. This will authenticate Joe through LDAP using his DN and password, as defined in the file.

6.2. Authenticating the User

To authenticate the user, Joe Simms, we need to create a new InitialDirContext object. This creates a connection to the directory server and authenticates the user through LDAP using his DN and password.

To do this, we first need to add these environment properties into a Hashtable:

Hashtable<String, String> environment = new Hashtable<String, String>();

environment.put(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
environment.put(Context.PROVIDER_URL, "ldap://localhost:10389");
environment.put(Context.SECURITY_AUTHENTICATION, "simple");
environment.put(Context.SECURITY_PRINCIPAL, "cn=Joe Simms,ou=Users,dc=baeldung,dc=com");
environment.put(Context.SECURITY_CREDENTIALS, "12345");

Next, inside a new method called authenticateUser, we’ll create the InitialDirContext object by passing the environment properties into its constructor. Then, we’ll close the context to free up resources:

DirContext context = new InitialDirContext(environment);
context.close();

Lastly, we’ll authenticate the user:

assertThatCode(() -> authenticateUser(environment)).doesNotThrowAnyException();

Now that we’ve covered the case where user authentication succeeds, let’s examine when it fails.

6.3. Handling User Authentication Failure

Applying the same environment properties as previously, let’s make the authentication fail by using the wrong password:

environment.put(Context.SECURITY_CREDENTIALS, "wrongpassword");

Then, we’ll check that authenticating the user with this password fails as expected:

assertThatExceptionOfType(AuthenticationException.class).isThrownBy(() -> authenticateUser(environment));

Next, let’s discuss how to authenticate the user when we don’t have his DN.

6.4. Looking up the User’s DN as Administrator

Sometimes when we want to authenticate a user, we don’t have his DN immediately at hand. In this situation, we first need to create a directory context with administrator credentials to look up the user’s DN and then authenticate the user with that.

As before, we first need to add some environment properties in a Hashtable. But this time, we’ll use the administrator’s DN as the Context.SECURITY_PRINCIPAL, together with his default admin password as the Context.SECURITY_CREDENTIALS property:

Hashtable<String, String> environment = new Hashtable<String, String>();

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

Next, we’ll create an InitialDirContext object with those properties:

DirContext adminContext = new InitialDirContext(environment);

This will create a directory context, with the connection to the server authenticated as the administrator. This gives us security rights to search for the user’s DN.

Now we’ll define the filter for our search based on the user’s CN, i.e., his common name.

String filter = "(&(objectClass=person)(cn=Joe Simms))";

Then, using this filter to search for the user, we’ll create a SearchControls object:

String[] attrIDs = { "cn" };
SearchControls searchControls = new SearchControls();
searchControls.setReturningAttributes(attrIDs);
searchControls.setSearchScope(SearchControls.SUBTREE_SCOPE);

Next, we’ll search for the user with our filter and SearchControls:

NamingEnumeration<SearchResult> searchResults
  = adminContext.search("dc=baeldung,dc=com", filter, searchControls);
  
String commonName = null;
String distinguishedName = null;
if (searchResults.hasMore()) {
    
    SearchResult result = (SearchResult) searchResults.next();
    Attributes attrs = result.getAttributes();
    
    distinguishedName = result.getNameInNamespace();
    assertThat(distinguishedName, isEqualTo("cn=Joe Simms,ou=Users,dc=baeldung,dc=com")));

    commonName = attrs.get("cn").toString();
    assertThat(commonName, isEqualTo("cn: Joe Simms")));
}

Let’s authenticate the user now that we have his DN.

6.5. Authenticating with the User’s Looked up DN

With the user’s DN now at hand to authenticate with, we’ll replace the administrator’s DN and password in the existing environment properties with the user’s ones:

environment.put(Context.SECURITY_PRINCIPAL, distinguishedName);
environment.put(Context.SECURITY_CREDENTIALS, "12345");

Then, with these in place, let’s authenticate the user:

assertThatCode(() -> authenticateUser(environment)).doesNotThrowAnyException();

Lastly, we’ll close the administrator’s context to free up resources:

adminContext.close();

7. Conclusion

In this article, we discussed how to use JNDI to authenticate a user with LDAP utilizing the user’s DN and password.

Also, we examined how to look up the DN if we don’t have it.

As usual, the complete source code for the examples can be found over on GitHub.

Course – LSS (cat=Security/Spring Security)

I just announced the new Learn Spring Security course, including the full material focused on the new OAuth2 stack in Spring Security:

>> CHECK OUT THE COURSE
res – Security (video) (cat=Security/Spring Security)
Comments are open for 30 days after publishing a post. For any issues past this date, use the Contact form on the site.