Integration of Spring Security with Spring LDAP Authentication in Spring Boot
Here’s an end-to-end example of integrating Spring Security with Spring LDAP for authentication in a Spring Boot application.
1. Set Up Local LDAP Server
To install and run an LDAP server locally, you can use Apache Directory Server or OpenLDAP. Here, I'll use Apache Directory Server (Apache DS) because it's easy to set up and works well with Spring Boot.
1.1. Install Apache Directory Server
Download Apache Directory Server from the official site.
- Choose the latest version based on your operating system.
Install Apache Directory Server:
- Extract the downloaded ZIP or tar.gz file to a directory of your choice.
- Open a terminal or command prompt and navigate to the directory where you extracted the server.
Start Apache Directory Server:
- Run the following command to start the LDAP server:
For Windows, use
bin/apacheds.bat start
.Access the Apache Directory Studio (optional) for easier interaction with your LDAP server:
- Download Apache Directory Studio (which provides a GUI to manage your LDAP data).
- Once downloaded, open it and connect to your LDAP server (usually,
localhost
on port10389
for the default installation).
Default credentials to connect:
- Username:
uid=admin,ou=system
- Password:
secret
1.2. Configure LDAP Directory
You can use the Apache Directory Studio or any other LDAP browser to create an entry in your LDAP server, such as a user. For example:
- DN (Distinguished Name):
uid=testuser,ou=users,dc=example,dc=com
- Attributes:
uid
,cn
,sn
,userPassword
You can also use LDIF (LDAP Data Interchange Format) to create the entries. Here's an example of an LDIF file to add a user:
2. Integrating Local LDAP with Spring Boot
Once the LDAP server is running, we can now configure Spring Boot to connect to the LDAP server.
2.1. Create Spring Boot Project
If you haven’t already created your Spring Boot project, use Spring Initializr and add the following dependencies:
- Spring Web
- Spring Security
- Spring LDAP
- Thymeleaf
You can also add Spring Boot DevTools for faster development and Spring Data LDAP for easier integration with Spring.
2.2. Add Configuration to application.properties
Configure the connection details to the local LDAP server in src/main/resources/application.properties
:
2.3. Create Spring Security Configuration
Next, create a configuration class to set up Spring Security to use LDAP authentication.
2.4. Create a Simple Controller
Create a simple controller with endpoints for login and home page.
2.5. Create login.html
and home.html
for Views
Create basic Thymeleaf templates in src/main/resources/templates/
for login and home.
login.html
:
home.html
:
2.6. Run the Application
Run your Spring Boot application using the following command:
Access the application at http://localhost:8080/
. You can log in using the LDAP credentials you created earlier (for example, uid=testuser,ou=users,dc=example,dc=com
with the password secret
).