Spring Boot教程(四十二)LDAP来管理用户信息(2)
- 使用 spring-data-ldap 的基础用法,定义 LDAP 中属性与我们 Java 中定义实体的关系映射以及对应的 Repository
12345678910111213141516171819
@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 suerName;
private
String userPassword;
}
public
interface
PersonRepository
extends
CrudRepository<Person, Name> {
}
通过上面的定义之后,已经将 Person 对象与 LDAP 存储内容实现了映射,我们只需要使用
PersonRepository
就可以轻松的对 LDAP 内容实现读写。 - 创建单元测试用例读取所有用户信息:
1234567891011121314
@RunWith
(SpringRunner.
class
)
@SpringBootTest
public
class
ApplicationTests {
@Autowired
private
PersonRepository personRepository;
@Test
public
void
findAll()
throws
Exception {
personRepository.findAll().forEach(p -> {
System.out.println(p);
});
}
}
启动该测试用例之后,我们可以看到控制台中输出了刚才维护在
ldap-server.ldif
中的用户信息:122018
-
01
-
27
14
:
25
:
06.283
WARN
73630
--- [ main] o.s.ldap.odm.core.impl.ObjectMetaData : The Entry
class
Person should be declared
final
Person(id=uid=ben,ou=people,dc=didispace,dc=com, uid=ben, commonName=didi, suerName=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 中添加用户:123456Person 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。
1234spring.ldap.urls=ldap:
//localhost:1235
spring.ldap.base=dc=didispace,dc=com
spring.ldap.username=didispace
spring.ldap.password=
123456
源码来源