SpringBoot集成LDAP

609 阅读3分钟

简介

LDAP,全称Lightweight Directory Access Protocol,中文译作轻量目录访问协议,是一个为查询、浏览和搜索而优化的数据库。它被设计成树状结构来组织数据,非常类似我们常见的文件目录。虽然目录数据库与关系数据库不同,它的读性能出类拔萃,但写性能较差,且缺乏事务处理、回滚等复杂功能,因此不适合存储需要频繁修改的数据。

作用

LDAP不仅仅是一种协议,更是一套基于该协议的系统。这个系统由目录数据库以及一套访问协议组成。这套开放的Internet标准是跨平台的,得到了业界的广泛认可。无论是商业产品还是开源社区的多数产品,都加入了对LDAP的支持。这就意味着对于这些系统,我们无需进行单独的定制,只需要通过LDAP进行简单的配置,就可以实现与服务器的认证交互。

如何集成SpringBoot

  • 集成SpringBoot的方法很简单,只需简单的引入maven依赖包,
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-data-ldap</artifactId>
</dependency>

配置方式

  • 1.在配置文件加入ldap连接配置
spring:
  ldap:
	# LDAP服务地址
    urls: ldap://127.0.0.1:389
	# 连接的基础域
    base: dc=demo,dc=cn
	# 用户
    username: cn=test1,dc=demo,dc=cn
	# 密码
    password: secret
  • 2.通过配置类进行配置
@Configuration
public class LdapConfig {
    /**
     * ad数据源配置
     *
     * @return
     */
    @Bean
    public LdapContextSource ldapContextSource() {
        LdapContextSource source = new LdapContextSource();
        source.setUserDn("cn=test1,dc=demo,dc=com");
        source.setPassword("secret");
        source.setBase("dc=demo,dc=com");
        source.setUrl("ldap://127.0.0.1:389");
        return source;
    }

    @Bean
    public LdapTemplate ldapTemplate() {
        return new LdapTemplate(ldapContextSource());
    }
}
  • 3.灵活动态配置 此方法配置较为灵活多变,需要使用的时候使用参数直接进行动态连接,需注意的是必须要调用方法source.afterPropertiesSet()才能够实现数据源生效
public static LdapTemplate buildLdapTemplate(String url, String userDn, String password, String base) {
	StringBuilder url = new StringBuilder();

	LdapContextSource source = new LdapContextSource();
	source.setUrl(url);
	source.setUserDn(userDn);
	source.setBase(base);
	source.setPassword(password);
	source.afterPropertiesSet();
	return new LdapTemplate(source);
}

使用LDAP查询

上面的步骤我们已经做到将数据源连接好了,接下来就是进行数据操作了。 在Spring项目直接注入LdapTemplate,如果是使用第三种方式配置的,直接获取LdapTemplate即可。

@Autowired
private LdapTemplate ldapTemplate;
  • LdapTemplate源码 下图是相关查询使用的方法,由于方法过多没有全部列出来,由此可见Ldap主要是用于数据高效查询的场景: 1697783399387.jpg

image.png

image.png

当然也少不了数据更新和删除了: image.png

image.png

案例

在这里我们也就简单的使用一些例子进行查询使用:

LdapQuery query = LdapQueryBuilder.query()
        .attributes("cn", "sn", "uid", "mail") // 需要进行查询的属性
        .where("objectClass").is("inetOrgPerson"); // 查询指定objectClass类型数据
// 使用AttributesMapper转换返回的数据结构
List<String> list = ldapTemplate.search(query, (AttributesMapper<String>) attrs -> (String) attrs.get("cn").get());

返回结果:

[
	{
		"cn": "test1",
		"mail": "test1@qq.com",
		"sn": "test111",
		"uid": "11111"
	},
	{
		"cn": "test2",
		"mail": "test2@qq.com",
		"sn": "test222",
		"uid": "22222"
	}
]

总结

LDAP历来被用作存储各种信息的数据库,其中包括用户的信息、用户的属性以及组成员的特权等等。LDAP是一种非常高效的查询工具,并被广泛应用在各种系统中。