使用LdapTemplate同步LDAP域用户信息

一、添加依赖

<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>

        <!-- Spring Boot Starter Data JPA -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>

        <!-- Spring Boot Starter LDAP -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-ldap</artifactId>
        </dependency>

        <!-- Spring Boot Starter Security -->
        <!--<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-security</artifactId>
        </dependency>-->
        
        <dependency>
            <groupId>org.springframework.ldap</groupId>
            <artifactId>spring-ldap-core</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.security</groupId>
            <artifactId>spring-security-ldap</artifactId>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
            <version>8.0.33</version>
        </dependency>
    </dependencies>

这里需要注意其中被注释掉的spring-boot-starter-security依赖,如果添加了security依赖就必须对其做配置,禁用CSRF,添加路径白名单等,如下示例:

package com.example.demo.config;

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;

@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.cors().and().csrf().disable()
                .authorizeRequests()
                .antMatchers("/api/syncUser", "/api/slaveData", "/api/masterData").permitAll()  // 允许匿名访问 /api/login
                .anyRequest().authenticated();
    }
}

二、配置文件如下

server.port = 28088
spring.application.name=LDAPServer

spring.datasource.url=jdbc:mysql://localhost:3306/nothing-phone
spring.datasource.username=root01
spring.datasource.password=localhost
spring.jpa.hibernate.ddl-auto=update
spring.jmx.enabled=true

#logging.level.org.springframework.ldap=DEBUG
#logging.level.root=DEBUG

三、配置LdapTemplate(关键且必要步骤)

在SpringBoot中,你需要配置一个LdapTemplate been,配置类如下:

package com.example.demo.config;
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;

@Configuration
public class LdapConfig {

    @Bean
    public LdapContextSource contextSource() {
        LdapContextSource contextSource = new LdapContextSource();
        contextSource.setUrl("ldap://172.30.60.2:3268");
        contextSource.setBase("OU=Tech,dc=noth,dc=local");
        contextSource.setUserDn("CN=ldapfordev,OU=Tech,dc=noth,dc=local");
        contextSource.setPassword("******");
        return contextSource;
    }

    @Bean
    public LdapTemplate ldapTemplate() {
        return new LdapTemplate(contextSource());
    }
}

四、创建域用户实体对象

package com.example.demo.model;

import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.extension.activerecord.Model;
import lombok.Data;
import lombok.EqualsAndHashCode;

@EqualsAndHashCode(callSuper = true)
@Data
public class LdapUsers extends Model<LdapUsers> {
    @TableId(type = IdType.AUTO)
    private Long id;
    private String name;
    private String displayName;
    private String memberOf;
    private String email;
    // Getters and Setters
}

五、在服务类使用LdapTemplate查询所有用户

package com.example.demo.service;

import com.baomidou.dynamic.datasource.annotation.DS;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.demo.mapper.LdapUsersMapper;
import com.example.demo.model.LdapUsers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ldap.core.AttributesMapper;
import org.springframework.ldap.core.LdapTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

import static org.springframework.ldap.query.LdapQueryBuilder.query;

@Service
public class UserSyncService {

    @Autowired
    private LdapTemplate ldapTemplate;

    @Resource
    private LdapUsersMapper ldapUsersMapper;


    @DS("slave")
    public void syncUsers() {
        // 从LDAP获取用户列表,并同步到本地数据库
        List<LdapUsers> ldapUsersList = fetchLdapUsers();
        System.out.println("域用户信息:"+ ldapUsersList.size());
        for (LdapUsers ldapUsers : ldapUsersList) {
            //如果不存在插入,存在则更新
            QueryWrapper queryWrapper = new QueryWrapper<LdapUsers>();
            queryWrapper.eq("name", ldapUsers.getName());
            if (!ldapUsersMapper.exists(queryWrapper)) {
                ldapUsersMapper.insert(ldapUsers);
            } else {
                LdapUsers existingUser = new LdapUsers();
                existingUser.setName(ldapUsers.getName());
                existingUser.setDisplayName(ldapUsers.getDisplayName());
                existingUser.setEmail(ldapUsers.getEmail());
                existingUser.setMemberOf(ldapUsers.getMemberOf());
                ldapUsersMapper.updateById(ldapUsers);
            }
        }
    }
	private List<LdapUsers> fetchLdapUsers() {
        // 实现LDAP用户获取逻辑
        List<LdapUsers> ldapUsers = ldapTemplate.search(
                query()
                        .where("objectClass").is("person"),
                (AttributesMapper<LdapUsers>) attributes -> {
                    LdapUsers user = new LdapUsers();
                    user.setName(attributes.get("sAMAccountName") != null?attributes.get("sAMAccountName").get().toString():"");
                    user.setDisplayName(attributes.get("displayname") != null?attributes.get("displayname").get().toString():"");
                    user.setMemberOf(attributes.get("distinguishedName") != null?attributes.get("distinguishedName").get().toString():"");
                    user.setEmail(attributes.get("mail") != null?attributes.get("mail").get().toString():"");
                    return user;
                });
        return ldapUsers;
    }

注意:@DS(“slave”)表示手动配置使用哪一个数据源。

六、控制类实现接口

package com.example.demo.controller;

import com.example.demo.service.UserSyncService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/api")
public class test {
    @Autowired
    UserSyncService userSyncService;
    
    @GetMapping("/syncUser")
    public ResponseEntity<String> sync() {
        userSyncService.syncUsers();
        return ResponseEntity.ok("Sync Completed");
    }
}

七、Mysql数据库

1、新建数据库

CREATE DATABASE nothing_dash_board;

2、新建表

CREATE TABLE `ldap_users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL,
  `display_name` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL,
  `member_of` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL,
  `email` varchar(255) COLLATE utf8mb4_bin DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=996 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;
SpringLDAP目录服务:LdapTemplate与LDAP操作 Spring LDAP为开发者提供了一个强大且灵活的框架,简化了与LDAP目录服务的交互。通过LdapTemplate,开发者可以轻松执行各种LDAP操作,而无需深入了解底层JNDI API的复杂性。对象-目录映射功能让LDAP条目与Java对象的转换变得简单直观,提高了代码的可读性和可维护性。与Spring Security的集成使得实现基于LDAP的身份验证和授权变得轻而易举。在企业应用中,特别是需要集中式用户管理的场景下,Spring LDAP是一个理想的选择。 阅读详情

相关推荐

获取和验证Windows AD域的用户信息

1、获取windows AD域用户信息,首先需要有一个ad域管理员权限的账号,用这个账号连接ad域,获取所有域用户信息 用LdapContext,它继承自DirContext public Object getAllAdUserNames() { List<String> list = new ArrayList<>(); ...

b078109的专栏 2488

Spring使用LdapTemplate进行LDAP操作

这里写目录标题LDAP基本概念示例代码常见问题1. LDAP基本概念2. 示例代码3. 常见问题3.1 ObjectSid,objectGUID乱码3.2 Java采用SSL连接AD域连接出错问题simple bind failed:IP:PORT解决方案3.3 添加,修改数组类型的AD属性3.4 javax.naming.CommunicationException:simple bind faild3.5 Spring's LdapTemplate search: PartialResultExcept

XSemperFI的博客 8110

LdapTemplate-开源

简化 LDAP 操作的 Java 框架,基于 Spring 的 JdbcTemplate 模式。 减轻用户查找和关闭上下文、循环命名枚举、编码/解码值和过滤器等的负担。

LDAP的介绍以及JAVA使用LdapTemplate来进行AD域的操作

AD是Active Directory的缩写,AD是LDAP的一个应用实例,而不应该是LDAP本身。比如:windows域控的用户、权限管理应该是微软公司使用LDAP存储了一些数据来解决域控这个具体问题,只是AD顺便还提供了用户接口,也可以利用ActiveDirectory当做LDAP服务器存放一些自己的东西而已。比如LDAP是关系型数据库,微软自己在库中建立了几个表,每个表都定义好了字段。显然这些表和字段都是根据微软自己的需求定制的,而不是LDAP协议的规定。

damokelisijian866的博客 3892

Python大数据舆情分析系统开发实战

舆情监测系统是大数据分析的重要应用场景,通过自然语言处理(NLP)技术解析社交媒体文本情感倾向。基于Python技术栈的解决方案整合了Scrapy爬虫框架进行数据采集,PySpark处理海量文本数据,结合SnowNLP和Jieba实现中文语义分析。系统采用微服务架构设计,包含数据采集层、处理层、存储层和应用层,通过情感分析优化和实时热点检测算法提升监测准确率。典型应用包括企业品牌监测、公共事件预警等场景,开发过程中需特别注意数据合规性和分布式集群的性能调优。

weixin_34408624的博客 388

自动驾驶IDM与MOBIL模型

IDM模型,自动驾驶

不想学好数学的汽车工程师不是一个好的程序员 1万+

【LDAP】Spring项目同步LDAP域用户信息总览(含ldapTemplate.search仅查询1000条数据的解决方案)

轻量级目录访问协议LDAP是一种开放的、供应商中立的行业标准应用协议,用于通过Internet 协议(IP) 网络访问和维护分布式目录信息服务。目录服务允许在整个网络中共享有关用户、系统、网络、服务和应用程序的信息,因此在开发Intranet和 Internet 应用程序中发挥着重要作用。例如,目录服务可以提供任何有组织的记录集,通常具有分层结构,例如公司电子邮件目录。类似地,电话簿也是具有地址和电话号码的用户列表。

Etui۹(・༥・´)و的博客 3522

英飞凌AURIX 2G 系列MCU关于外设模块EVADC的实现原理及对应MCAL(EB Tresos)配置项详细讲解

本文章讲述了英飞凌AURIX 2G系列MCU关于外设模块EVADC的实现原理及对应MCAL配置工具(EB)的配置项。

weixin_46176506的博客 6276

使用Spring的LdapTemplate进行LDAP操作

使用Spring的LdapTemplate进行LDAP操作 本文来源于铁木箱子的博客http://www.mzone.cc 本文永久地址是:http://www.mzone.cc/article/621.html &lt;!-- 日志内容 --&gt;       最近利用空闲时间研究了一把LDAP,然后用spring进行了一些编程尝试,通过spring的LdapTemplate可...

咖啡堂 1914

74HC138译码器的原理和使用

A0,A1,A2为3位二进制加权地址输入端口,A2A1A0顺序组成的3位2进制数对应的十进制数x控制使能端口Yx';例如当A2A1A0 = 101 时,其他门输出端全为高电平,只有Y5'为低电平。 Y0-Y7为8个输出端口,其输出电平由A0,A2,A3,E1,E2,E3决定。

diksan的博客 6万+

Cadence 17.2配置CIS数据库报错?手把手解决ODBC驱动位数不匹配问题

本文详细解析了Cadence 17.2配置CIS数据库时常见的ODBC驱动位数不匹配问题,提供了从系统环境检查到分步解决方案的完整指南。重点解决32位应用程序与64位ODBC驱动之间的架构冲突,包含驱动安装、DSN配置及高级排查技巧,帮助电子工程师快速恢复设计环境。

play7的博客 971

SpringCloud中ldapTemplate操控LDAP

参数括号里面的为对象,括号前的为描述 |代表可以有多中参数,代表多个参数 1.常用操作 名称 说明 备注 参数 ldapTemplate LDAP模板 操作LDAP的基类 .lookup 获取LDAP中的对象 ldapTemplate中的方法 DN(String|Name) .lookupContext 获取LDAP中的对象 ldapTemplate中的方法,调用的也同样是lookup方法 DN(String|Name) .bind 添加LDAP中的对象 ldapTemplat

weixin_44728369的博客 2080

使用Simulink对基于GaN器件的高频电源进行建模与仿真,重点在于优化其效率

本文介绍了基于Simulink的GaN器件高频电源仿真建模方法。通过7个步骤详细讲解系统构建过程:从创建模型、设置电源、配置GaN开关网络,到添加磁性元件、负载和控制器设计,最后进行仿真分析。重点探讨了效率优化策略,包括开关频率选择、磁性元件优化、散热设计改进及控制策略调整。该教程为GaN器件在电力电子系统中的应用提供了完整的仿真流程指导,有助于设计人员验证方案并优化性能。

amy_mhd的博客 234

Springboot使用LDAP集成AD域,实现用户认证、检索用户、重置密码

文章目录一、基本概念理解和注意事项二、代码实现1. 引入依赖2. 在`application.yml`中配置ldap(s)连接信息3. 生成和导入ssl证书4. 创建domain类`Person.java`5. `ILdapService.java`6. `LdapServiceImpl.java`三、常见错误排除References 一、基本概念理解和注意事项 LDAP客户端工具 二、代码实现 1. 引入依赖 2. 在application.yml中配置ldap(s)连接信息 3. 生成和导入ssl证

WWF_HelloWorld 2万+

Openclaw错误排查及解决方案之:Something went wrong while processing your request. Please try again.

Openclaw错误排查及解决方案之:Something went wrong while processing your request. Please try again.

多媒体编程、网络编程、系统编程、网络安全编程、驱动编程 3790

基于STM32、HAL库的BMP585 气压传感器 驱动程序设计

define BMP585_I2C_ADDR_PRIMARY 0x76 << 1 /* 0x76地址左移一位 */#define BMP585_I2C_ADDR_SECONDARY 0x77 << 1 /* 0x77地址左移一位 *//* I2C句柄 *//* I2C地址 *//* 设置新的温度过采样率 *//* 设置新的滤波器系数 *//* 芯片ID *//* 清除温度过采样位 *//* 转换为hPa *//* 设置新的压力过采样率 *//* 设置新的电源模式 *//* 清除压力过采样位 */

corlin6688的博客 461

SpringMVC + Ldap 整合,LdapTemplate使用

一、什么是LDAP? LDAP(Light Directory Access Portocol),它是基于X.500标准的轻量级目录访问协议。 目录是一个为查询、浏览和搜索而优化的数据库,它成树状结构组织数据,类似文件目录一样。 目录数据库和关系数据库不同,它有优异的读性能,但写性能差,并且没有事务处理、回滚等复杂功能,不适于存储修改频繁的数据。所以目录天生是用来查询的,就好象它的名字一样。 LDAP目录服务是由目录数据库和一套访问协议...

zhua.er的博客 5892

C# WinForm 基于DirectShow.dll编写的程序,可边预览边保存视频,音频和图片

基于微软的DirectShow.dll的二次开发1.自动识别连接的摄像头跟麦克风且可以对其进行选择(默认选中第一个)2.可录制wmv和avi两种格式的视频并且都带有音频,avi可以录制的分辨率和帧数进行选择,wmv默认进行了淸晰度优化如不喜欢可去除代码中有相关提示3.可在预览点开之后进行拍照,也可边录制视频边拍照4.添加了视频和音频的压缩功能(酌情使用)这次二次开发发现C#对DirectShow的相关信息太少,这次做完也不敢藏私共享出来,还望大家指正

LdapTemplate+springBoot

Ldap+springBoot

huonan_123的博客 5118

文档:亲测可用解决vnc灰屏,黑屏,鼠标大黑叉情况

主要解决vnc-viewer灰屏,黑屏,鼠标大黑叉等现象,详细见文档。

STM32F407中文手册

STM32f407中文手册 本参考手册面向应用开发人员,提供有关使用 STM32F405xx/07xx、STM32F415xx/17xx、 STM32F42xxx 和 STM32F43xxx 微控制器存储器与外设的完整信息。STM32F405xx/07xx、STM32F415xx/17xx、STM32F42xxx 和 STM32F43xxx 构成一个微 控制器系列,各产品具有不同的存储器大小、封装和外设。有关订购信息以及器件的机械与电气特性,请参见数据手册。有关 ARM Cortex™-M4F 内核的信息,请参见《Cortex™-M4F 技术参考手册》。

ldaptemplate 查询

最近利用空闲时间研究了一把LDAP,然后用spring进行了一些编程尝试,通过spring的LdapTemplate可以很方便的进行LDAP的CRUD操作。如果你不清楚啥是LDAP的话,可以查询相关资料后再看此文。一般来说LDAP可以用来作为一个用户中心,围绕LDAP可以部署一些应用来共享相同的账号,这个在企业管理中是非常有帮助的,因为企业的内部应用可能是几个到几十个,员工如果有统一的账号密码,那

Take pains, and be perfect 3327

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

Java通过Spring的LdapTemplate操作LDAP

Java通过Spring的LdapTemplate操作LDAP 1、添加maven依赖 &lt;dependency&gt; &lt;groupId&gt;org.springframework.ldap&lt;/groupId&gt; &lt;artifactId&gt;spring-ldap-core&lt;/artifactId&gt; &lt;version&gt;2.3...

mry6的博客 1万+

spring boot中使用LdapTemplate操作ldap

配置LdapTemplate import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.ldap.core.LdapTemplate; import org.s.

csdn_meng的博客 2114

java ldap ssl_LdapTemplate忽略ssl证书

一、背景最近做JAVA的LDAP操作,使用的是Spring的LdapTemplate,基本上一个bean注入就完成了LdapTemplate的初始化,正常连接389端口,现在要要试一下HTTPS的连接方式spring.ldap:urls: ldap://ip:389base: dc=xxx,dc=comusername: xxxpassword: xxx@Beanpublic LdapTempla...

weixin_42723849的博客 1479

SpringBoot 集成 LDAP获取用户信息

欲买桂花同载酒,终不似、少年游。 --唐多令·芦叶满汀洲

Soutv - Hello Bug ! 8853
上一篇: SpringBoot+Mybatis-Plus实现多数据源使
下一篇: LDAP域单点登录认证并生成JWT
Senye_ing
博客等级 码龄8年 24粉丝 21原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Senye_ing

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值