SpringBoot --- 整合Ldap

  • 1.介绍
  • 2.代码
    • 2.1 pom.xml
    • 2.2 配置文件
    • 2.3 代码

整理不易,不喜勿喷。谢谢

SpringBoot — 整合Ldap.
SpringBoot — 整合Spring Data JPA.
SpringBoot — 整合Elasticsearch.
SpringBoot — 整合spring-data-jpa和spring-data-elasticsearch.
SpringBoot — 整合thymeleaf.
SpringBoot — 注入第三方jar包.
SpringBoot — 整合Redis.
Springboot — 整合slf4j打印日志.
Springboot — 整合定时任务,自动执行方法.
Springboot — 配置多数据源,使用JdbcTemplate以及NamedParameterJdbcTemplate.
Sprignboot — 详解pom.xml中build和profile.
SpringBoot — 监控.
SpringBoot — 缓存Cache/Redis.
SpringBoot与Zookeeper.
Git的使用.

1.介绍

缩写 全称 内容
DC Domain Component 域名的部分,其格式是将完整的域名分成几部分,如域名为example.com变成dc=example,dc=com
UID User Id 用户ID songtao.xu(一条记录的ID)
OU Organization Unit 组织单位,组织单位可以包含其他各种对象(包括其他组织单元),如“oa组”(一条记录的所属组织)
CN Common Name 公共名称,如“Thomas Johansson”(一条记录的名称)
SN Surname 姓,如“许”
DN Distinguished Name “uid=songtao.xu,ou=oa组,dc=example,dc=com”,一条记录的位置(唯一)
RDN Relative dn 相对辨别名,类似于文件系统中的相对路径,它是与目录树结构无关的部分,如“uid=tom”或“cn= Thomas Johansson”
  • Ldap连接服务器的连接字串格式为:ldap://servername/port
  • 例如:CN=test,OU=developer,DC=domainname,DC=com
    在上面的代码中 cn=test 可能代表一个用户名,ou=developer 代表一个 active directory 中的组织单位。这句话的含义可能就是说明 test 这个对象处在domainname.com 域的 developer 组织单元中。

2.代码

2.1 pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.4.5</version><relativePath/> <!-- lookup parent from repository --></parent><groupId>com.nolan</groupId><artifactId>spring-boot-ldap</artifactId><version>0.0.1-SNAPSHOT</version><name>spring-boot-ldap</name><description>Demo project for Spring Boot</description><properties><java.version>1.8</java.version></properties><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-ldap</artifactId></dependency><dependency><groupId>org.apache.commons</groupId><artifactId>commons-lang3</artifactId><version>3.5</version></dependency><dependency><groupId>org.projectlombok</groupId><artifactId>lombok</artifactId><optional>true</optional></dependency></dependencies><build><plugins><plugin><groupId>org.springframework.boot</groupId><artifactId>spring-boot-maven-plugin</artifactId></plugin></plugins></build></project>

2.2 配置文件

server.port=8086spring.ldap.urls=ldap://xxxx:xxxx
spring.ldap.base=OU=xxx,DC=xxx,DC=xxxspring.ldap.username=CN=xxxx,OU=xxxx,OU=Users,OU=xxx,OU=xx,OU=xxx,DC=xxxx,DC=corp
spring.ldap.password=Mxxxx

2.3 代码

1.service

@Service
public interface LdapService {List<LdapUser> getPersonList();List<LdapDept> getDeptList();boolean authenticate(String user, String pwd);
}
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.NamingException;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.support.LdapUtils;
import org.springframework.stereotype.Service;import javax.naming.NamingEnumeration;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.DirContext;
import java.util.List;import static org.springframework.ldap.query.LdapQueryBuilder.query;@Service
public class LdapServiceImpl implements LdapService {@Autowiredprivate LdapTemplate ldapTemplate;/*** 获得域用户*/@Override@SuppressWarnings({"rawtypes", "unchecked"})public List<LdapUser> getPersonList() {//下面也可以使用filter查询方式,filter 为(&(objectClass=user)(!(objectClass=computer))return ldapTemplate.search(query().where("objectclass").is("user").and("objectclass").not().is("computer"),new AttributesMapper() {@Overridepublic LdapUser mapFromAttributes(Attributes attr) throws NamingException, javax.naming.NamingException {//如果不知道ldap中有哪些属性,可以使用下面这种方式打印System.out.println("==============start ldap person attribute==============================");NamingEnumeration<? extends Attribute> att = attr.getAll();while (att.hasMore()) {Attribute a = att.next();System.out.println(a.getID());}System.out.println("==============上面是ldap person attribute==============================");LdapUser person = new LdapUser();String distingugihedName = (String) attr.get("distinguishedName").get();person.setUserName((String) attr.get("sAMAccountName").get());person.setRealName((String) attr.get("cn").get());String departmentName = StringUtils.substringAfter(distingugihedName.split(",")[1], "OU=");person.setUnitName(departmentName);if (attr.get("description") != null) {person.setDescription((String) attr.get("description").get());}if (attr.get("mobile") != null) {person.setPhone((String) attr.get("mobile").get());}if (attr.get("telephoneNumber") != null) {person.setTelephone((String) attr.get("telephoneNumber").get());}if (attr.get("userPrincipalName") != null) {person.setEmail((String) attr.get("userPrincipalName").get());}return person;}});}/*** 获得部门*/@Override@SuppressWarnings({"rawtypes", "unchecked"})public List<LdapDept> getDeptList() {return ldapTemplate.search(query().where("objectclass").is("organizationalunit").or("objectclass").is("organization"),new AttributesMapper() {@Overridepublic LdapDept mapFromAttributes(Attributes attr) throws NamingException {//如果不知道ldap中有哪些属性,可以使用下面这种方式打印// NamingEnumeration<? extends Attribute> att = attr.getAll();//while (att.hasMore()) {//  Attribute a = att.next();// System.out.println(a.getID());//}LdapDept dept = new LdapDept();dept.setDeptId(attr.get("ou").toString().split(":")[1].trim());if (attr.get("description") != null) {dept.setDeptName(attr.get("description").toString().split(":")[1].trim());}return dept;}});}/*** 根据用户名密码验证** @param username 用户名* @param pwd    密码* @return*/@SuppressWarnings("unchecked")@Overridepublic boolean authenticate(String username, String pwd) {DirContext ctx = null;System.out.println(username + ":" + pwd);try {//调用ldap 的 authenticate方法检验String filter = "(&(objectclass=user)(!(objectClass=computer))(sAMAccountName=" + username + "))";boolean authenticate = ldapTemplate.authenticate("", filter, pwd);return authenticate;} catch (Exception e) {e.printStackTrace();return false;} finally {LdapUtils.closeContext(ctx);}}
}

2.entity

@Data
public class LdapDept {private String deptId;private String deptName;
}
@Data
public class LdapUser {private String userName;private String email;private String phone;private String telephone;private String realName;private String unitName;private String description;
}

3.config

import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.ldap.core.support.LdapContextSource;import java.util.HashMap;
import java.util.Map;@Configuration
public class LdapConfig {private LdapTemplate ldapTemplate;@Value("${spring.ldap.urls}")private String url;@Value("${spring.ldap.base}")private String base;@Value("${spring.ldap.username}")private String username;@Value("${spring.ldap.password}")private String password;@Beanpublic LdapContextSource contextSource() {LdapContextSource contextSource = new LdapContextSource();Map<String, Object> config = new HashMap();contextSource.setUrl(url);contextSource.setBase(base);contextSource.setUserDn(username);contextSource.setPassword(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;}}

SpringBoot --- 整合Ldap相关推荐

  1. springboot 整合 LDAP

    springboot 整合 LDAP 1.添加依赖 <dependency><groupId>org.springframework.boot</groupId>& ...

  2. springboot整合ldap

    LDAP介绍 介绍 LDAP是域的一种管理系统. LDAP的存储结构为树状结构,由父节点.子节点.叶子节点组成. 概念 Entry 条目,LDAP系统中最基本的颗粒,类似于数据库的记录.通常对LDAP ...

  3. SpringBoot集成Ldap

    目录 什么是Ldap 为什么需要Ldap Ldap基本模型 Springboot集成Ldap Springboot操作Ldap 什么是Ldap 轻型目录访问协议(英文:Lightweight Dire ...

  4. SpringBoot第九篇: springboot整合Redis

    这篇文章主要介绍springboot整合redis,至于没有接触过redis的同学可以看下这篇文章:5分钟带你入门Redis. 引入依赖: 在pom文件中添加redis依赖: <dependen ...

  5. es springboot 不设置id_原创 | 一篇解决Springboot 整合 Elasticsearch

    ElasticSearch 结合业务的场景,在目前的商品体系需要构建搜索服务,主要是为了提供用户更丰富的检索场景以及高速,实时及性能稳定的搜索服务. ElasticSearch是一个基于Lucene的 ...

  6. springboot整合shiro使用shiro-spring-boot-web-starter

    此文章仅仅说明在springboot整合shiro时的一些坑,并不是教程 增加依赖 <!-- 集成shiro依赖 --> <dependency><groupId> ...

  7. db2 springboot 整合_springboot的yml配置文件通过db2的方式整合mysql的教程

    springboot整合MySQL很简单,多数据源就master,slave就行了,但是在整合DB2就需要另起一行,以下是同一个yml文件 先配置MySQL,代码如下 spring: datasour ...

  8. 九、springboot整合rabbitMQ

    springboot整合rabbitMQ 简介 rabbitMQ是部署最广泛的开源消息代理. rabbitMQ轻量级,易于在内部和云中部署. 它支持多种消息传递协议. RabbitMQ可以部署在分布式 ...

  9. 八、springboot整合Spring Security

    springboot整合Spring Security 简介 Spring Security是一个功能强大且可高度自定义的身份验证和访问控制框架.它是保护基于Spring的应用程序的事实标准. Spr ...

最新文章

  1. I.MX6 Android frameworks services 文件架构
  2. php redis 用户注册,redis+php实现微博(一)注册与登录功能详解
  3. python~文件遍历命令:glob、os.walk
  4. MySQL count函数的具体介绍
  5. frp内网穿透-公网IP低成本使用高性能kali
  6. ubuntu php7 memcache,linux上安装php7 memcache扩展
  7. ubuntu更改mysql编码格式_Ubuntu修改mysql编码格式
  8. 2019蓝桥杯A组:数列求值(递推式)
  9. 区块链应用 | 区块链的火爆会一直持续吗?
  10. 《Python金融大数据风控建模实战》 第14章 决策树模型
  11. linux按行将两个txt合并成一个文件
  12. icem二维非结构网格划分_【史上最全轴承结构化网格划分系列】第五弹——自动校准滚针轴承(文末附模型领取方式)...
  13. #pragma comment(lib 的用法
  14. ES文件浏览器★显示永久VIP会员★去盗版弹窗
  15. 安防摄像头有这么多种类,如何正确选择?
  16. 【大学生软件测试基础】web版微信登录测试 - 正交表
  17. java.lang.RuntimeException:Unable to start activity ComponentInfo{com.meizu.beautify/com.my.viewc.Ma
  18. 买Mac做设计玩游戏?各类Mac图形设计能力浅析
  19. iOS中数组拼接方法
  20. 【shell案例】一个脚本让你从此再也不怕删错文件

热门文章

  1. redis分布式锁原理及实现
  2. Unity3D 在一加5T手机上USB调试
  3. 计算机毕业设计node+vue基于微信小程序的美甲店铺座位预约系统的设计与实现 uniapp 小程序
  4. WebGoat8 M17 JWT tokens 题解
  5. 16 岁少年前往腾讯总部要求解封 QQ 账号;微软发内部信辟谣:没有关闭微软苏州的相关计划;Go 1.20 发布|极客头条...
  6. TCP长连接实践与挑战
  7. vue computed原理
  8. 昨天刷爆朋友圈的趣味翻译,你看到了吗?
  9. 在线生成彩字在线制作动态特效文字的2个网站
  10. 开启IDEA工具的service运行窗口