关于Java LDAP登录集成
最近项目需要集成LDAP的登录,所以简单研究了一下ldap的集成主要有以下几个步骤:
一、配置spring boot的LDAP配置文件
1.配置pom文件:
<dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-ldap</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> <exclusions> <exclusion> <groupId>org.junit.vintage</groupId> <artifactId>junit-vintage-engine</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.62</version> </dependency> </dependencies>
2.配置LDAP的数据元信息:
spring.ldap.urls=ldap://127.0.0.1:389 spring.ldap.base=DC=dc-test,DC=com spring.ldap.username=cn=cnName,ou=ouName,dc=dc-test,dc=com spring.ldap.password=******
这样配置就可以正常的查询ldap的数据信息了
二、查询实例:
ldapTemplate.lookup("OU=ouName", new AttributesMapper<Object>() { @Override public Object mapFromAttributes(Attributes attributes) throws NamingException { return attributes; } });
一开始一直不能查询到数据提示:
org.springframework.ldap.NameNotFoundException: [LDAP: error code 32 - 0000208D: NameErr: DSID-03100238, problem 2001 (NO_OBJECT), data 0, best match
原因其实就是查询的条件不对,我这边查询的时候应该从我这边给定的ou开始查询比如我这边给定的是ouName所以应该从ouName开始查询,如果要查询下级则需要两个条件一起输入查询比如
ldapTemplate.lookup("OU=ouNameNext,OU=ouName", new AttributesMapper<Object>() { @Override public Object mapFromAttributes(Attributes attributes) throws NamingException { return attributes; } });
注意结构应该是左边是下级部门,右边是上级部门
三、最后递归查询所有的部门及成员信息:
@Test public void getAllTree() { List<NameClassPair> nameList = new ArrayList<>(); getCurrentDept("OU=ouName", nameList); } private void getCurrentDept(String base, List<NameClassPair> nameList) { List<NameClassPair> nameClassPairMapperList = ldapTemplate.list(base, new NameClassPairMapper() { @Override public NameClassPair mapFromNameClassPair(NameClassPair nameClassPair) throws NamingException { return nameClassPair; } }); if (nameClassPairMapperList.size() == 0) { return; } for (NameClassPair nameClassPair : nameClassPairMapperList) { // System.out.println(nameClassPair.getNameInNamespace().substring(0, nameClassPair.getNameInNamespace().indexOf("DC") - 1)); getCurrentDept(nameClassPair.getNameInNamespace().substring(0, nameClassPair.getNameInNamespace().indexOf("DC") - 1), nameList); } nameList.addAll(nameClassPairMapperList); }