我在最近的一个企业项目中,需要在 SpringBoot 服务中接入公司内部的 LDAP(Lightweight Directory Access Protocol)服务器,用于员工的统一认证和信息查询。网上相关的资料比较零散,不够系统,于是我把整个配置和实现的过程记录下来,希望能帮助到正在学习 SpringBoot 或正在做 LDAP 集成的开发者。
1. 为什么要在 SpringBoot 中使用 LDAP?
在很多企业应用中,LDAP 目录服务常常被用来作为用户信息和权限的统一入口。通过在 SpringBoot 中集成 LDAP,我们可以:
- 实现统一的用户认证,不必在系统里重复维护用户表。
- 查询用户的组织、邮箱、职位等信息,方便权限管理。
- 提升系统的可维护性和安全性。
如果你正准备把 SpringBoot 应用对接公司内部的 LDAP 服务器,那么这篇文章正好适合你。
2. 添加依赖(pom.xml)
在 pom.xml
文件中添加 Spring LDAP 相关依赖:
<dependencies>
<!-- Spring Boot LDAP 支持 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-ldap</artifactId>
</dependency>
<!-- Spring Boot Web 模块 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
</dependencies>
3. 配置文件(application.yml)
在 application.yml
中配置 LDAP 服务器连接参数:
spring:
ldap:
urls: ldap://localhost:389 # LDAP 服务器地址
base: dc=example,dc=com # 基础搜索路径
username: cn=admin,dc=example,dc=com # 管理员账号
password: admin_password # 管理员密码
⚠ 注意:
urls
配置项要写完整的协议和端口号,比如ldap://
。
4. 定义实体类
使用注解将 LDAP 条目映射成 Java 实体类,例如定义一个 LdapUser
:
import org.springframework.ldap.odm.annotations.*;
import javax.naming.Name;
@Entry(base = "ou=users", objectClasses = {"inetOrgPerson", "organizationalPerson"})
public class LdapUser {
@Id
private Name dn;
@Attribute(name = "uid")
private String uid;
@Attribute(name = "cn")
private String fullName;
@Attribute(name = "sn")
private String surname;
@Attribute(name = "mail")
private String email;
// getter 和 setter 省略
}
这里的 @Entry
注解表明该对象对应 LDAP 中的用户条目。
5. Repository 层
通过继承 LdapRepository
,我们可以非常方便地对 LDAP 数据进行查询:
import org.springframework.data.ldap.repository.LdapRepository;
import org.springframework.stereotype.Repository;
@Repository
public interface LdapUserRepository extends LdapRepository<LdapUser> {
LdapUser findByUid(String uid);
}
6. Service 层
在服务层封装业务逻辑,避免直接在 Controller 调用 Repository:
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class LdapUserService {
@Autowired
private LdapUserRepository ldapUserRepository;
public LdapUser getUserByUid(String uid) {
return ldapUserRepository.findByUid(uid);
}
}
7. 控制器测试
定义一个简单的接口用于测试:
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/ldap")
public class LdapController {
private final LdapUserService ldapUserService;
public LdapController(LdapUserService ldapUserService) {
this.ldapUserService = ldapUserService;
}
@GetMapping("/user/{uid}")
public LdapUser getUser(@PathVariable String uid) {
return ldapUserService.getUserByUid(uid);
}
}
访问:http://localhost:8080/ldap/user/testuser
,即可从 LDAP 查询用户信息。
8. 总结
本文主要分享了 SpringBoot 整合 LDAP 的完整步骤,包括:
- Maven 依赖配置
- application.yml 参数设置
- 实体类定义
- Repository + Service + Controller 三层代码实现