Member-only story
How to Query the Active Directory Using Spring Boot LdapTemplate
LDAP queries with Spring Boot LdapTemplate

If you do not have a medium membership, you can still read this here.
Recently, I was playing around with the Active Directory (AD) and tried to retrieve user information via LDAP Queries. It was definitely a frustrating experience as I wasn’t very familiar with LDAP. Hence, I decided to write about what I have learned.
Note: at the point of writing, I am working with Spring Boot v2.7.7, Gradle v7.6, Docker-Compose v2.14.0, Docker v20.10.3, and Java v11.
Overview
Let’s start with a bit of background context. An Active Directory (AD) is a commonly used directory service by many companies for user & group management, policy administration, authentication, and etc… LDAP (Lightweight Directory Access Protocol) is a protocol that we can use to communicate with the LDAP servers (eg. the AD).
When developing services, we can authenticate users with LDAP or retrieve user information from the LDAP server. In this article, I will focus mainly on some of the methods I used to query the LDAP server using LdapTemplate
. The LdapTemplate
is a set of ready-to-use APIs for executing core LDAP operations such as creation, modification, retrieval, etc…
Setting up a LDAP Server
Before we start, we will need to have an LDAP server to query. In this demo, instead of setting up an entire Active Directory, we will set up an LDAP server using osixia/docker-openldap
. This is an OpenLDAP docker image that allows us to easily populate the LDAP database using an LDIF file.
To get started, we will prepare a bootstrap LDIF file that contains all the data that we want to seed the LDAP database with. For demonstration purposes, we will only be populating the LDAP database with some user information as shown below.