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

宝塔面板添加站点及运营商SSL免费证书的申请与使用

本文详细介绍在宝塔面板下如何正确添加站点、配置站点,及在运营商如何申请免费SSL证书,将其配置到宝塔站点里。 给你的网站加一把锁,教你免费SSL证书申请,配置到自己的网站中。 环境:Ubuntu server 18 工具:宝塔控制面板 平台:阿里云 Web服务器:Nginx 宝塔:https://www.bt.cn/ 阿里云:https://www.aliyun.com/ 腾讯云:https://cloud.tencent.com/ 要求: 1.宝塔控制面板搭建完毕。 2掌握域名解析的原理。 3.了解ht

贺兰山长老 5059

华中农业大学C++考试基础练习题

实验一 1 通过日期求某月的天数。 输入日期的年份和月份,求该月有多少天。提示:对于月份为1、3、5、7、8、10、12的月份天数为31,月份为4、6、9、11的月份天数为30,月份为2时要结合年份考虑闰年的情况。 输入描述 输入两个正整数y和m分别表示年份和月份。 输出描述 如果y和m满足条件:1900<=y<3000,0<m<13,输出该月的天数;否则输出“Input error!”。 输入样例 2010 12 输出样例 31 #include"iostream" using n

雨的博客 1万+

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

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

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

从零复刻平衡小车(基于STM32F1)

平衡小车(基于STM32F1)

Legendyyy的博客 5041

使用Spring的LdapTemplate进行LDAP操作

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

咖啡堂 1914

人工智能情感分析实战:文本情绪识别

人工智能情感分析,特别是文本情绪识别,已成为理解和处理人类情感信息的重要工具。通过数据预处理、特征提取、模型训练与评估等步骤,我们可以有效地从文本数据中提取情感信息,为各种应用场景提供有价值的洞察。随着技术的不断进步和创新,情感分析的应用前景将更加广阔,为我们的生活和工作带来更多便利和机遇。

shejizuopin的博客 1097

FreeRTOS深入教程(任务创建的深入和任务调度机制分析)

本篇文章将带大家深入学习任务的创建和分析任务调度的机制。本篇文章深入的讲解了任务创建的内部实现和任务调度的源代码分析和实现,学习这篇文章有助于更深入的学习FreeRTOS的源码。

m0_49476241的博客 6391

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

喷涂机器人系列编程:ABB IRB 5500_(9).常见故障诊断与排除

ABB IRB 5500 喷涂机器人在实际应用中可能会遇到各种故障,但通过系统的诊断和排除方法,可以确保生产线的连续运行。定期维护和保养是预防故障的重要手段,而操作培训和规范则能有效减少人为因素引起的故障。希望本节内容能帮助操作和维护人员提高故障诊断和排除的效率,确保喷涂机器人的稳定运行。如果您有任何疑问或需要进一步的帮助,请联系 ABB 客户服务中心。

zhubeibei168的博客 1045

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从入门到精通】第60篇:多智能体协同实战——用“龙虾”搭建你的数字员工团队(2026企业版)

2026年AI Agent企业落地的核心趋势,正从“单Agent单兵作战”转向“多智能体协同组网”。本文以全球开发者先锋大会“百虾大战”真实案例为蓝本,深度拆解OpenClaw多智能体协同的技术内核——三层解耦架构(模型层-技能层-网关层),系统搭建包含项目经理、架构师、执行者、质量把关者的4大核心Agent团队。通过三种主流协作架构对比、全链路配置代码实操、故障自愈实战演练,结合电商新品上架虚拟场景全流程演示,解决企业多Agent部署中的权限隔离、任务协同、运维自治三大核心痛点。

专注于人工智能、软件开发、工控自动化、工厂数字化及智能化等领域,希望和大家共同进步! 769

Lammps实现随机粗糙度表面沸腾

Lammps实现随机粗糙度表面沸腾前言 前言

Rockyoung 2703

SpringMVC + Ldap 整合,LdapTemplate使用

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

zhua.er的博客 5892

霍尼韦尔SoftMaster使用说明

霍尼韦尔SoftMaster使用说明

LdapTemplate+springBoot

Ldap+springBoot

huonan_123的博客 5118

jdk-8u144-linux-x64.tar.gz.

该资源为搭建Linux系统Java环境用,资源的后缀为tar.gz格式的压缩包

RU DOS版、EFI版32bit/64bit BIOS常用工具

DOS版、EFI版的RU工具,可用来查看IO、MEM、PCI、SMBIOS等资源。亲测在EFI SHELL下可用。

ldaptemplate 查询

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

Take pains, and be perfect 3327

win10 跳过U8环境检测的IE WebControls.rar

win10 安装u8的时候 提示IE WebControls 不通过,这个工具可以欺骗u8的检查。 跳过U8环境检测的IE WebControls。提示导入失败后,重新检测通过。

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、付费专栏及课程。

余额充值