使用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;
评论
成就一亿技术人!
拼手气红包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、付费专栏及课程。

余额充值