eBook – Guide Spring Cloud – NPI EA (cat=Spring Cloud)
announcement - icon

Let's get started with a Microservice Architecture with Spring Cloud:

>> Join Pro and download the eBook

eBook – Mockito – NPI EA (tag = Mockito)
announcement - icon

Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.

Get started with mocking and improve your application tests using our Mockito guide:

Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Reactive – NPI EA (cat=Reactive)
announcement - icon

Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:

>> Join Pro and download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Jackson – NPI EA (cat=Jackson)
announcement - icon

Do JSON right with Jackson

Download the E-book

eBook – HTTP Client – NPI EA (cat=Http Client-Side)
announcement - icon

Get the most out of the Apache HTTP Client

Download the E-book

eBook – Maven – NPI EA (cat = Maven)
announcement - icon

Get Started with Apache Maven:

Download the E-book

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

eBook – RwS – NPI EA (cat=Spring MVC)
announcement - icon

Building a REST API with Spring?

Download the E-book

Course – LS – NPI EA (cat=Jackson)
announcement - icon

Get started with Spring and Spring Boot, through the Learn Spring course:

>> LEARN SPRING
Course – RWSB – NPI EA (cat=REST)
announcement - icon

Explore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:

>> The New “REST With Spring Boot”

Course – LSS – NPI EA (cat=Spring Security)
announcement - icon

Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.

I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.

You can explore the course here:

>> Learn Spring Security

Course – LSD – NPI EA (tag=Spring Data JPA)
announcement - icon

Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.

Get started with Spring Data JPA through the guided reference course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Partner – LambdaTest – NPI EA (cat=Testing)
announcement - icon

Regression testing is an important step in the release process, to ensure that new code doesn't break the existing functionality. As the codebase evolves, we want to run these tests frequently to help catch any issues early on.

The best way to ensure these tests run frequently on an automated basis is, of course, to include them in the CI/CD pipeline. This way, the regression tests will execute automatically whenever we commit code to the repository.

In this tutorial, we'll see how to create regression tests using Selenium, and then include them in our pipeline using GitHub Actions:, to be run on the LambdaTest cloud grid:

>> How to Run Selenium Regression Tests With GitHub Actions

Course – LJB – NPI EA (cat = Core Java)
announcement - icon

Code your way through and build up a solid, practical foundation of Java:

>> Learn Java Basics

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 JndiLdapAuthManualTest full 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.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Baeldung Pro – NPI EA (cat = Baeldung)
announcement - icon

Baeldung Pro comes with both absolutely No-Ads as well as finally with Dark Mode, for a clean learning experience:

>> Explore a clean Baeldung

Once the early-adopter seats are all used, the price will go up and stay at $33/year.

eBook – HTTP Client – NPI EA (cat=HTTP Client-Side)
announcement - icon

The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:

>> Download the eBook

eBook – Java Concurrency – NPI EA (cat=Java Concurrency)
announcement - icon

Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.

Get started with understanding multi-threaded applications with our Java Concurrency guide:

>> Download the eBook

eBook – Java Streams – NPI EA (cat=Java Streams)
announcement - icon

Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.

But these can also be overused and fall into some common pitfalls.

To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:

>> Join Pro and download the eBook

eBook – Persistence – NPI EA (cat=Persistence)
announcement - icon

Working on getting your persistence layer right with Spring?

Explore the eBook

Course – LS – NPI EA (cat=REST)

announcement - icon

Get started with Spring Boot and with core Spring, through the Learn Spring course:

>> CHECK OUT THE COURSE

Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – LSS – NPI (cat=Security/Spring Security)
announcement - icon

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

eBook Jackson – NPI EA – 3 (cat = Jackson)