前言
因為項目要根據租戶不同連接不同ldap服務器,要給租戶管理員提供一個ldap配置頁面,并提供測試連接ldap服務器測試功能。
代碼
spring-boot-starter-data-ldap是直接在application文件中配置即可
(私人信息用**表示了)
ldap:
url: ldap://ldap.**.**:389
base: DC=**,DC=**
username: ***
password: *****
referral: follow
提供測試功能,連接多個ldap服務器,sysConfigParam頁面配置信息和application配置一致。
LdapContextSource ldapContextSource = new LdapContextSource();
ldapContextSource.setBase(sysConfigParam.getBase());
ldapContextSource.setUrl(sysConfigParam.getUrl());
ldapContextSource.setPassword(sysConfigParam.getPassword());
ldapContextSource.setUserDn(sysConfigParam.getUsername());
ldapContextSource.setReferral(sysConfigParam.getReferral());
ldapContextSource.afterPropertiesSet();
DirContext ctx = null;
try {
// Ldap link
ctx = ldapContextSource.getReadOnlyContext();
System.out.println("[auth ldap linked] InitialDirContext success");
} catch (Exception e) {
throw new ServiceException(SysLdapConfigExceptionEnum.DATA_SOURCE_NOT_EXIST);
} finally {
if (ctx != null) {
try {
ctx.close();
} catch (NamingException e) {
throw new ServiceException(SysLdapConfigExceptionEnum.DATA_SOURCE_NOT_EXIST);
}
}
}