一、添加依赖
<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;
1851






