LDAP入门http://www.jianshu.com/p/7e4d99f6baaf

  • Spring LDAP,是Spring的一个组件,实现对LDAP的操作。

  • 在编程操作MySQL时,我们除了用JDBC,可能都会选用一些框架,比如JbdcTemplate。

  • JdbcTemplate的实现是通过传入sql语句和RowMapper,query返回目标列表,或是传入sql和参数,执行update方法。JdbcTemplate的优点是简化了与数据库连接的代码,以及避免了一些常见的错误。

  • 同样的,Spring LDAP框架也提供了类似的特性——LdapTemplate。

  • 优点都是相通的,Spring LdapTemplate的优点是简化了与LDAP交互的代码。

  • 按之前Spring配置JavaBean的方式,在xml文件配置LdapTemplate及其属性值即可,本文将演示使用Springboot 用Java代码的方式定义LdapTemplate,完成Spring ldap连接数据库服务及进行相关操作。

下面是使用Spring-ldap的依赖

<!-- spring ldapTemplate操作 --><dependency><groupId>com.sun</groupId><artifactId>ldapbp</artifactId><version>1.0</version></dependency><dependency><groupId>org.springframework.ldap</groupId><artifactId>spring-ldap-core</artifactId><version>2.3.2.RELEASE</version></dependency>
  • 先介绍一些Spring-ldap,因为网上有很多教程,在给出的工程依赖中有用spring-ldap的,也有spring-ldap-core的,而且还有版本问题。笔者使用目前最新的spring-ldap-2.3.2.RELEASE。推荐直接使用,这个最新版本。

  • spring-ldap框架,是Spring集成ldap操作的总和,包含spring-ldap-core,spring-ldap-core-tiger,spring-ldap-ldif-core,spring-ldap-odm等jar,而通常我们在工程中只需要引入spring-ldap-core即可,它提供了绝大部分功能。而且截至目前,spring-ldap的<version>2.3.2.RELEASE</version>不在maven的中央仓库,不好获取。但spring-ldap-core在。

  • 另外,Spring LDAP 2.0对jdk版本要求是1.6,并且开始支持ODM,并后来引入Spring ldap pool连接池。

  • 据本人尝试,这些版本之间,变化差异很大。在新版本中可能有些关键的核心类,都会被移动到不同的package下;一些老版本完成的愚钝功能,可能在新版本中有了更好的实现或支持,所以在新版本中,一些“愚钝”实现可能会被移除。

  • 比如LdapTemplate,原先在org.springframework.ldap包,在最新版本被移至core包。在spring-ldap-core的<version>2.0.2.RELEASE</version>版本中支持类似于JPA方式的LdapRepository,但在2.3.2最新版本中,完全被移除,但是新版本增强的LdapTemplate,使得LdapTemplate功能更强大,可以完全替代LdapRepository。

下面是用Java代码的方式定义LdapTemplate,完成用Spring ldap连接LDAP服务器:

import com.xxx.xxx.sim.ldap.constants.LdapConstans;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.ldap.core.ContextSource;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource;
import org.springframework.ldap.pool.factory.PoolingContextSource;
import org.springframework.ldap.pool.validation.DefaultDirContextValidator;
import org.springframework.ldap.transaction.compensating.manager.TransactionAwareContextSourceProxy;
import java.util.HashMap;
import java.util.Map;/*** LDAP 的自动配置类** 完成连接 及LdapTemplate生成*/
@Configuration
public class LdapConfiguration {private LdapTemplate ldapTemplate;@Beanpublic LdapContextSource contextSource() {LdapContextSource contextSource = new LdapContextSource();Map<String, Object> config = new HashMap();contextSource.setUrl(LdapConstans.url);contextSource.setBase(LdapConstans.BASE_DC);contextSource.setUserDn(LdapConstans.username);contextSource.setPassword(LdapConstans.password);//  解决 乱码 的关键一句config.put("java.naming.ldap.attributes.binary", "objectGUID");contextSource.setPooled(true);contextSource.setBaseEnvironmentProperties(config);return contextSource;}@Beanpublic LdapTemplate ldapTemplate() {if (null == ldapTemplate)ldapTemplate = new LdapTemplate(contextSource());return ldapTemplate;}}
  • 完成LdapTemplate的bean定义,是最关键的一步。因为后续的操作,对于LDAP目录树的CRUD操作,全都靠它完成。
  • 通过上面的代码,在IOC容器完成bean的定义,我们在外部就可以注入使用LdapTemplate了。

下面给出用LdapTemplate完成CRUD功能:

import com.xxx.xxx.sim.ldap.attribute.LdapDeptAttributeMapper;
import com.xxx.xxx.ldap.attribute.LdapUserAttributeMapper;
import com.xxx.xxx.xxx.ldap.module.dto.LdapUser;
import org.junit.Assert;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.core.DirContextAdapter;
import org.springframework.ldap.core.DistinguishedName;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.filter.AndFilter;
import org.springframework.ldap.filter.EqualsFilter;
import java.util.List;public class ConfigTest extends BaseTest {@Autowiredprivate LdapTemplate ldapTemplate;/*** 获取所有 internal人员* ou=Internal,ou=People*/@Testpublic void listUsers(){AndFilter filter = new AndFilter();filter.and(new EqualsFilter("objectClass", "person"));//查询所有内部人员List<LdapUser> users = ldapTemplate.search("ou=internal,ou=People", filter.encode(), new LdapUserAttributeMapper());for (LdapUser user: users ) {System.out.println(user);}//        Assert.assertEquals(123, users.size());}/*** 根据userid 查找单个人员*/@Testpublic void findUser(){//uid=123,ou=internal,ou=People,o=xxx.com,o=xxxDirContextAdapter obj = (DirContextAdapter) ldapTemplate.lookup("uid=123,ou=internal,ou=People");//BASE_DC 不用填System.out.println(obj);}/*** 根据部门编号o,查找部门*/@Testpublic void findDept(){//o=abcd,ou=Organizations,ou=People,o=xxx.com,o=xxxDirContextAdapter obj = (DirContextAdapter) ldapTemplate.lookup("o=abcd,ou=Organizations");//BASE_DC 不用填System.out.println(obj);}@Testpublic void listDepts(){AndFilter filter = new AndFilter();filter.and(new EqualsFilter("objectClass", "organization"));//search是根据过滤条件进行查询,第一个参数是父节点的dn,可以为空,不为空时查询效率更高List depts = ldapTemplate.search("", filter.encode(), new LdapDeptAttributeMapper());System.out.println(depts.size());
//        Assert.assertEquals(305600, depts.size());}
}
  • 在ldap中,有两个"查询"概念,search和lookup。search是ldaptemplate对每一个entry进行查询,lookup是通过DN直接找到某个条目。
  • 在Ldap中,新增与删除叫做绑定bind和解绑unBind。这些方法LdapTemplate全部提供,并且还提供各种条件过滤等方法,不如findAll(),list()等。

我们注意到,findAll(),list()肯定是返回一个java.util.List<T>,包括,

//查询所有internal人员
List<LdapUser> users = ldapTemplate.search("ou=internal,ou=People", filter.encode(), new LdapUserAttributeMapper());

也是返回列表,列表里装的是查询出来的结果。但是上一篇文章用JNDI方式查询出来的是
Attributes attrs = ctx.getAttributes("uid=123,ou=Internal,ou=People");//获取到一个人员
Spring-ldap是基于JNDI实现的封装,那是哪里实现的把Attributes转成我们需要的Java Bean对象呢?
答案在new LdapUserAttributeMapper(),这个接口实现了查询结果到对象的转化。

import com.xxx.csb.sim.ldap.module.dto.LdapUser;
import org.springframework.ldap.core.AttributesMapper;
import javax.naming.NamingException;
import javax.naming.directory.Attributes;/*** 将ldap返回的结果,转成指定对象*/
public class LdapUserAttributeMapper implements AttributesMapper {/*** 将单个Attributes转成单个对象* @param attrs* @return* @throws NamingException*/public Object mapFromAttributes(Attributes attrs) throws NamingException {LdapUser user  = new LdapUser();if(attrs.get("uid") != null){user.setUsername( attrs.get("uid").get().toString());}if(attrs.get("cn") != null){user.setUserCn( attrs.get("cn").get().toString());}if(attrs.get("mobile") != null){user.setMobile( attrs.get("mobile").get().toString());}if(attrs.get("mail") != null){user.setMail( attrs.get("mail").get().toString());}if(attrs.get("employeeNumber") != null){user.setUserNumber( attrs.get("employeeNumber").get().toString());}if(attrs.get("type") != null){user.setUserType( attrs.get("type").get().toString());}if(attrs.get("py") != null){user.setPinyin(attrs.get("py").get().toString());}if(attrs.get("alias") != null){user.setAlias(attrs.get("alias").get().toString());}if(attrs.get("departmentNumber") != null){user.setDeptId(attrs.get("departmentNumber").get().toString());}if(attrs.get("departmentName") != null){user.setDeptName(attrs.get("departmentName").get().toString());}if(attrs.get("jobname") != null){user.setPositionName(attrs.get("jobname").get().toString());}if(attrs.get("modifyTimestamp") != null){user.setModifyTimestamp(attrs.get("modifyTimestamp").get().toString());}return user;}
}

可以看到转化的过程非常繁琐,无非就是拿JNDI查询到的Attributes,不停的获取属性值,再设置到Java对象中;attrs.get("uid").get().toString()然后set。

那好了,在每次查询的时候,要查询到多少列,在这个AttributesMapper转化方法中就要写多少个,判断及赋值。而且,如果因为业务不同,要查询不同的列,那AttributesMapper接口的实现必须重新写。那有没有支持复用的方式呢?答案是肯定的。下节分享spring ldap ODM , Object-Directory Mapping。

spring-ldap-2.3.2.RELEASE所有jar包下载
http://download.csdn.net/download/ljheee/10150501

Spring-ldap最新版官方文档:
https://docs.spring.io/spring-ldap/docs/2.3.2.RELEASE/reference/

作者:消失er
链接:https://www.jianshu.com/p/3aeb49a9befd
来源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

Spring LDAP的使用相关推荐

  1. Spring LDAP

    LDAP Spring LDAP 使用 - Sayi像秋天一样优雅 - 开源中国社区 http://docs.spring.io/spring-ldap/docs/current/reference/ ...

  2. Spring LDAP 2.0.0发布

    Spring团队很高兴宣布Spring LDAP 2.0.0已发布,并且现在可以从Maven Central和Bintray获得. Spring LDAP 2.0.0.RELEASE Released ...

  3. Security——Spring LDAP

    Spring LDAP 依赖说明:使构建使用轻量级目录访问协议的基于 Spring 的用用程序变得更容易. DAP的英文全称是Lightweight Directory Access Protocol ...

  4. 【数据库】LDAP 的概念与 Spring LDAP 框架使用

    文章目录 1 ldap 是什么 2 ldap 基本模型 2.1 数据模型 2.2 命名模型 2.3 功能模型 2.4 安全模型 3 openLDAP服务器 4 Spring LDAP 4.1 构建 L ...

  5. Spring系列学习之Spring LDAP

    英文原文:https://spring.io/projects/spring-ldap 目录 概述 LDAP 快速开始 学习 文档 概述 LDAP LDAP是轻量目录访问协议,英文全称是Lightwe ...

  6. ssha java接口_java – 从Spring在LDAP中设置SSHA密码

    我在解决如何使用SSHA哈希而不是纯文本在Apache DS LDAP中保存密码时遇到问题.据我所知,正确的方法应该是配置Apache DS以使用SSHA存储密码,然后在设置密码时只发送纯文本.但是, ...

  7. Spring Boot中使用LDAP来统一管理用户信息

    很多时候,我们在构建系统的时候都会自己创建用户管理体系,这对于开发人员来说并不是什么难事,但是当我们需要维护多个不同系统并且相同用户跨系统使用的情况下,如果每个系统维护自己的用户信息,那么此时用户信息 ...

  8. spring ldap_Spring 3,Spring Web Services 2和LDAP安全

    spring ldap 今年的开局很好,其中另一个"截止日期不会改变" /"跳过所有繁文tape节" / "狂野西部"类型的项目中,我必须弄 ...

  9. Spring Boot 2.x基础教程:使用LDAP来管理用户与组织数据

    很多时候,我们在做公司系统或产品时,都需要自己创建用户管理体系,这对于开发人员来说并不是什么难事,但是当我们需要维护多个不同系统并且相同用户跨系统使用的情况下,如果每个系统维护自己的用户信息,那么此时 ...

最新文章

  1. 手把手教你JavaEE的分页查询、分页展示,有了这个,你的项目又多了一个谈资
  2. day3----编码-集合-深浅copy-文件操作-函数初识
  3. MVVM实践中的Command与CommandParameter的使用
  4. 互联网大鳄的成长模式
  5. 数据结构:线性数据结构(3)-deques(栈,队列,deques, 列表)
  6. mysql binlog线程恢复_使用MySQL SQL线程回放Binlog实现恢复
  7. hive 多用户访问模注意问题
  8. java阻塞锁_java – 阻止锁与非阻塞锁
  9. python 操作excel 教程_Python学习笔记(十六)—Python操作Excel
  10. Java常见OutOfMemoryError
  11. python程序字符串中字符排序_python字符串排序方法
  12. 容器技术Docker K8s 2 云原生容器技术概述
  13. 242.有效的字母异位词
  14. 雷神开机logo更改_Win10系统怎样更改开机logo
  15. linux拷贝安装包到另一个目录下,把windows下的压缩包放到Linux目录下去
  16. 【目标检测】目标检测算法-从OverFeat到YOLO
  17. macOS:卸载JRE或JDK
  18. appiume连接逍遥模拟器
  19. #html#画哆啦a梦
  20. 最优布线问题 题解

热门文章

  1. 我的伟大航路(12)
  2. 星戈瑞Sulfo-CY7 NHS ester标记带氨基的荧光Cyanine7-NHS
  3. 视频行业风云变幻 PPTV半年“功力”猛增
  4. 迅为IMX6开发板适用于HMI|车载电脑|工业控制|医疗仪器|智能家居 灵活进行产品开发平台...
  5. 基于JAVA酒店预约及管理系统计算机毕业设计源码+数据库+lw文档+系统+部署
  6. 杭州端点科技两轮面试总结,共勉
  7. broforce怎呢上机器人_机器人怎么玩 机器人的出装 暴力机器人 详情介绍
  8. 家装建材企业打开网络营销的正确姿势
  9. MSP430F5529学习笔记(2)——点亮LED
  10. MFC Windows 程序设计[108]之取色器(附源码)