Spring-Security with LDAP物件關係(整理中)

本篇主要記載Spring-Security-LDAP中,我們有使用到的物件去做說明。我們目的是整合LDAP與AD驗證,其中為了滿足我們的需求,有對不少Spring所提供的物件做擴充。這部分有機會再另外分享。

以我的範例來說,首先會透過資料庫做登入認證,接著會是AD,最後是LDAP。而透過程式碼配置的方式,會去extend WebSecurityConfigurerAdapter;接著override configure的method,AuthenticationManagerBuilder可以讓你配置AuthenticationProvider:

@Autowired
@Qualifier("dataSource")
DataSource datasource;
 
@Autowired
@Qualifier("ldapConfig")
Properties ldapConfig;
 
@Autowired
@Qualifier("adConfig")
Properties adConfig;
 
@Override
protected void configure(AuthenticationManagerBuilder aAuth) throws Exception {
	aAuth.jdbcAuthentication().dataSource(datasource);	
 
	String domain = (String)adConfig.get("ad.domain");
	String url = (String)adConfig.get("ad.url");
	ActiveDirectoryLdapAuthenticationProvider adProvider = new ActiveDirectoryLdapAuthenticationProvider(domain, url);
	aAuth.authenticationProvider(adProvider);
 
	aAuth.ldapAuthentication()
		 .groupSearchBase(ldapConfig.get("ldap.groupSearchBase"))
		 .groupSearchFilter(StringUtil.apendStrings(ldapConfig.get("ldap.groupSearchAttr"), "={0}"))
		 .userSearchBase(ldapConfig.get("ldap.userSearchBase"))
		 .userSearchFilter(StringUtil.apendStrings(ldapConfig.get("ldap.userSearchAttr"), "={0}"))
		 .contextSource()
		 .url(StringUtil.apendStrings("ldap://", ldapConfig.get("ldap.host"), ":", ldapConfig.get("ldap.port"), "/", ldapConfig.get("ldap.baseDn")))
		 .managerDn(ldapConfig.get("ldap.managerDn"))
		 .managerPassword(ldapConfig.get("ldap.managerPassword"));
}
以上程式碼的三個主要部分為:

  • jdbcAuthentication(): 建立JdbcUserDetailsManager去透過資料庫做驗證。
  • ldapAuthentication(): 建立LdapAuthenticationProvider去透過Ldap做驗證。
  • authenticationProvider(): 將ActiveDirectoryLdapAuthenticationProvider加到Provider列表中,去透過AD做驗證。


假如你想做更多的變化,也可以自行實做AuthenticationProvider將這些東西串起來。

AuthenticationProvider是驗證的核心。舉例來說,使用者在登入畫面輸入了帳號密碼,最後就會透過authenticate method做驗證;其中傳入的Authentication會包含帳號密碼,回傳的則包含使用者權限:

Authentication authenticate(Authentication authentication) throws AuthenticationException;
Authentication比較重要的methods:

  • Object getCredentials(): 密碼。
  • Object getPrincipal(): 帳號。
  • Collection<? extends GrantedAuthority> getAuthorities(): 泛指權限。


接著對LDAP與AD的AuthenticationProvider做說明。