基于 spring-boot-starter-data-ldap
,实现了正式的绑定-认证
的AD域认证逻辑。
简述
基于LDAP认证的流程如下:
- 业务系统持有一个可以连接到
LDAP Server
进行用户查询的内置账号【绑定用户
】。 - 业务系统使用
绑定用户
作为LDAP Client
与LDAP Server
建立连接。 - 连接建立后,业务系统将
待认证用户信息
传递给LDAP Server
进行验证。LDAP Server
验证结束后将认证结果返回给业务系统。 - 如果
LDAP
认证通过,业务系统执行内部登录授权过程。
代码实现
- 导包
<!--ldap-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-ldap</artifactId>
</dependency>
- 配置连接参数
spring:
ldap:
urls: ldap://1.1.1.1
base: OU=user,DC=company,DC=com
username: softdev.user@company.com
password: ******
- 在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;
}
- 使用
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
)。
网友评论