Spring Boot LDAP/AD認證

基于 spring-boot-starter-data-ldap,實現(xiàn)了正式的綁定-認證的AD域認證邏輯。

簡述

基于LDAP認證的流程如下:

  1. 業(yè)務系統(tǒng)持有一個可以連接到LDAP Server進行用戶查詢的內置賬號【綁定用戶】。
  2. 業(yè)務系統(tǒng)使用綁定用戶作為LDAP ClientLDAP Server建立連接。
  3. 連接建立后,業(yè)務系統(tǒng)將待認證用戶信息傳遞給LDAP Server進行驗證。LDAP Server驗證結束后將認證結果返回給業(yè)務系統(tǒng)。
  4. 如果LDAP認證通過,業(yè)務系統(tǒng)執(zhí)行內部登錄授權過程。

代碼實現(xiàn)

  1. 導包
<!--ldap-->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-ldap</artifactId>
</dependency>
  1. 配置連接參數(shù)
spring:
  ldap:
    urls: ldap://1.1.1.1
    base: OU=user,DC=company,DC=com
    username: softdev.user@company.com
    password: ******
  1. 在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;
}
  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)。

?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

友情鏈接更多精彩內容