Spring Boot 2.0 项目实现自同步AD域账号
时间: 2023-07-12 11:54:23 浏览: 177
Springboot-LDAP针对AD域控做用户和组织进行同步.zip
实现自同步AD域账号需要借助Spring Security的LDAP模块。以下是基本步骤:
1. 在pom.xml中添加Spring Security和LDAP依赖。
```
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-ldap</artifactId>
<version>5.4.1</version>
</dependency>
<dependency>
<groupId>org.springframework.ldap</groupId>
<artifactId>spring-ldap-core</artifactId>
<version>2.3.3.RELEASE</version>
</dependency>
```
2. 配置LDAP连接信息,包括URL、用户名、密码等。
```
spring.ldap.urls=ldap://ldap.example.com:389
spring.ldap.base=dc=example,dc=com
spring.ldap.username=cn=admin,dc=example,dc=com
spring.ldap.password=secret
```
3. 创建一个LDAPUserDetailsMapper,将LDAP用户映射为Spring Security的UserDetails对象。
```
@Component
public class CustomUserDetailsContextMapper extends LdapUserDetailsMapper {
@Override
public UserDetails mapUserFromContext(DirContextOperations ctx, String username,
Collection<? extends GrantedAuthority> authorities) {
// 将LDAP用户属性映射到UserDetails对象中
String fullName = ctx.getStringAttribute("cn");
String email = ctx.getStringAttribute("mail");
String password = ctx.getStringAttribute("userPassword");
List<GrantedAuthority> grantedAuthorities = new ArrayList<>(authorities);
return User.withUsername(username)
.password(password)
.authorities(grantedAuthorities)
.build();
}
}
```
4. 配置LDAP认证Provider,使用上面创建的LDAPUserDetailsMapper将LDAP用户转换为Spring Security的UserDetails对象。
```
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Autowired
private CustomUserDetailsContextMapper customUserDetailsContextMapper;
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.anyRequest().authenticated()
.and()
.formLogin();
}
@Override
protected void configure(AuthenticationManagerBuilder auth) throws Exception {
auth.ldapAuthentication()
.userDetailsContextMapper(customUserDetailsContextMapper)
.userSearchFilter("(sAMAccountName={0})")
.userSearchBase("ou=Users,dc=example,dc=com")
.groupSearchBase("ou=Groups,dc=example,dc=com")
.groupSearchFilter("(member={0})")
.contextSource()
.url("ldap://ldap.example.com:389/dc=example,dc=com")
.managerDn("cn=admin,dc=example,dc=com")
.managerPassword("secret");
}
}
```
5. 在定时任务中使用LDAP模板查询AD域用户并将其同步到本地数据库。
```
@Service
public class LdapSyncService {
@Autowired
private LdapTemplate ldapTemplate;
@Autowired
private UserRepository userRepository;
@Scheduled(fixedDelay = 3600000)
public void syncUsers() {
List<User> users = ldapTemplate.search(
"ou=Users,dc=example,dc=com",
"(objectclass=user)",
new UserAttributesMapper());
userRepository.saveAll(users);
}
}
```
这样就可以实现自同步AD域账号了。注意要根据实际情况修改LDAP连接信息和查询过滤条件。
阅读全文