objectclass: top
objectclass: organizationalUnit
ou: people
dn: uid=ben,ou=people,dc=didispace,dc=com
objectclass: top
objectclass: person
objectclass: organizationalPerson
objectclass: inetOrgPerson
cn: didi
sn: zhaiyongchao
uid: didi
userPassword: {SHA}nFCebWjxfaLbHHG1Qk5UU4trbvQ=
这里创建了一个基础用户,真实姓名为zhaiyongchao
,常用名didi
,在后面的程序中,我们会来读取这些信息。更多内容解释大家可以深入学习LDAP来理解,这里不做过多的讲解。
- 在
application.properties
中添加嵌入式LDAP的配置
spring.ldap.embedded.ldif=classpath:ldap-server.ldif
spring.ldap.embedded.base-dn=dc=didispace,dc=com
- 使用spring-data-ldap的基础用法,定义LDAP中属性与我们Java中定义实体的关系映射以及对应的Repository
@Data
@Entry(base = “ou=people,dc=didispace,dc=com”, objectClasses = “inetOrgPerson”)
public class Person {
@Id
private Name id;
@DnAttribute(value = “uid”, index = 3)
private String uid;
@Attribute(name = “cn”)
private String commonName;
@Attribute(name = “sn”)
private String userName;
private String userPassword;
}
public interface PersonRepository extends CrudRepository<Person, Name> {
}
通过上面的定义之后,已经将Person对象与LDAP存储内容实现了映射,我们只需要使用PersonRepository
就可以轻松的对LDAP内容实现读写。
- 创建单元测试用例读取所有用户信息:
@Slf4j
@SpringBootTest
public class ApplicationTests {
@Autowired
private PersonRepository personRepository;
@Test
public void findAll() {
personRepository.findAll().forEach(p -> {
System.out.println§;
});
}
}
启动该测试用例之后,我们可以看到控制台中输出了刚才维护在ldap-server.ldif
中的用户信息:
Person(id=uid=ben,ou=people,dc=didispace,dc=com, uid=ben, commonName=didi, userName=zhaiyongchao, userPassword=123,83,72,65,125,110,70,67,101,98,87,106,120,102,97,76,98,72,72,71,49,81,107,53,85,85,52,116,114,98,118,81,61)
添加用户
通过上面的入门示例,如果您能够独立完成,那么在Spring Boot中操作LDAP的基础目标已经完成了。
如果您足够了解Spring Data,其实不难想到,这个在其下的子项目必然也遵守Repsitory的抽象。所以,我们可以使用上面定义的PersonRepository
来轻松实现操作,比如下面的代码就可以方便的往LDAP中添加用户:
Person person = new Person();
person.setUid(“uid:1”);
person.setSuerName(“AAA”);
person.setCommonName(“aaa”);
person.setUserPassword(“123456”);
personRepository.save(person);
如果还想实现更多操作,您可以参考spring-data-ldap的文档来进行使用。
连接LDAP服务端
在本文的例子中都采用了嵌入式的LDAP服务器,事实上这种方式也仅限于我们本地测试开发使用,真实环境下LDAP服务端必然是独立部署的。
在Spring Boot的封装下,我们只需要配置下面这些参数就能将上面的例子连接到远端的LDAP而不是嵌入式的LDAP。
spring.ldap.urls=ldap://localhost:1235
spring.ldap.base=dc=didispace,dc=com
spring.ldap.username=didispace
spring.ldap.password=123456
关注我,后面更新如何与Spring Security结合使用!
最后
笔者已经把面试题和答案整理成了面试专题文档
![image](https://upload-images.jianshu.io/upload_images/24616006-6b74605caeef162e?imageMogr2/auto-orient
必看视频!获取2024年最新Java开发全套学习资料 备注Java
/strip%7CimageView2/2/w/1240)
View2/2/w/1240)
[外链图片转存中…(img-OWQ6EeQt-1716356317882)]
[外链图片转存中…(img-fFBwik77-1716356317882)]
[外链图片转存中…(img-P0hu8pzr-1716356317883)]
[外链图片转存中…(img-Zj3v2RfC-1716356317883)]
[外链图片转存中…(img-Rrz5GF1r-1716356317883)]