基于 spring-boot-starter-data-ldap,實現(xiàn)了正式的綁定-認證的AD域認證邏輯。
簡述
基于LDAP認證的流程如下:
- 業(yè)務系統(tǒng)持有一個可以連接到
LDAP Server進行用戶查詢的內置賬號【綁定用戶】。 - 業(yè)務系統(tǒng)使用
綁定用戶作為LDAP Client與LDAP Server建立連接。 - 連接建立后,業(yè)務系統(tǒng)將
待認證用戶信息傳遞給LDAP Server進行驗證。LDAP Server驗證結束后將認證結果返回給業(yè)務系統(tǒng)。 - 如果
LDAP認證通過,業(yè)務系統(tǒng)執(zhí)行內部登錄授權過程。
代碼實現(xiàn)
- 導包
<!--ldap-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-ldap</artifactId>
</dependency>
- 配置連接參數(shù)
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數(shù)據(jù)源
*/
@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)。