Spring Boot LDAP/AD认证

基于 spring-boot-starter-data-ldap,实现了正式的绑定-认证的AD域认证逻辑。

简述

基于LDAP认证的流程如下:

  1. 业务系统持有一个可以连接到LDAP Server进行用户查询的内置账号【绑定用户】。
  2. 业务系统使用绑定用户作为LDAP ClientLDAP Server建立连接。
  3. 连接建立后,业务系统将待认证用户信息传递给LDAP Server进行验证。LDAP Server验证结束后将认证结果返回给业务系统。
  4. 如果LDAP认证通过,业务系统执行内部登录授权过程。

代码实现

  1. 导包


    org.springframework.boot
    spring-boot-starter-data-ldap

  1. 配置连接参数
spring:
  ldap:
    urls: ldap://1.1.1.1
    base: OU=user,DC=company,DC=com
    username: [email protected]
    password: ******
  1. 在Spring Boot中初始化LdapTemplate
/**
 * 配置AD数据源
 */
@Configuration
@EnableConfigurationProperties(LdapProperties.class)
public class LdapConfig {
    @Bean
    public LdapContextSource ldapContextSource() {
        LdapContextSource source = new LdapContextSource();
        source.setUserDn(properties.getUsername());
        source.setPassword(properties.getPassword());
        source.setBase(properties.getBase());
        source.setUrls(properties.determineUrls(environment));
        source.setBaseEnvironmentProperties(Collections.unmodifiableMap(properties.getBaseEnvironment()));
        return source;
    }

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

    @Autowired
    private LdapProperties properties;

    @Autowired
    private Environment environment;
}
  1. 使用LdapTemplate进行身份认证
/**
 * AD认证
 *
 * @param username 用户名
 * @param password 密码
 */
boolean ldapAuth(String username, String password) {
    EqualsFilter filter = new EqualsFilter("sAMAccountName", username);
    return ldapTemplate.authenticate("", filter.toString(), password);
}

@Autowired
private LdapTemplate ldapTemplate;

注:对于微软AD域服务来说,认证的用户名对应sAMAccountName。其他类型的LDAP服务可能使用别的attribute来进行认证(比如uid)。

你可能感兴趣的:(Spring Boot LDAP/AD认证)