如何為 Spring Security 編寫認證提供者
1. 概述
本教程將會展示如何創建一個Spring Security 的認證提供者,來獲得比標準場景下使用的簡單的UserDetailsService 更多的靈活性。
2. 認證提供者
Spring Security 對執行認證提供了多樣的選擇 – 所有選擇都基于一個約定 – 即一個 Authentication 請求由一個 AuthenticationProvider 來處理并且返回一個被完全認證的、具有所有憑證的對象。
標準的、最常用的實現是 DaoAuthenticationProvider – 它獲取用戶詳細信息是通過一個簡單的只讀的用戶DAO,即 UserDetailsService 。當我們想要獲取完整的用戶實體時,UserDetailsService 卻僅能訪問用戶名 – 然而在大部分情況下,這已經足夠了。
更多用戶自定義的情境下,為了完成認證過程,將需要訪問完整的Authentication 請求 – 例如,當針對一些外部、第三方的服務(比如Crowd)進行認證時 – 來自于認證請求中的 username 和 password 都是必須的。
對這些更高級的場景,我們將需要定義一個自定義的認證提供者:
@Component public class CustomAuthenticationProvider implements AuthenticationProvider {@Override public Authentication authenticate(Authentication authentication) throws AuthenticationException { String name = authentication.getName(); String password = authentication.getCredentials().toString(); // use the credentials to try to authenticate against the third party system if (authenticatedAgainstThirdPartySystem()) { List<GrantedAuthority> grantedAuths = new ArrayList<>(); return new UsernamePasswordAuthenticationToken(name, password, grantedAuths); } else { return null; } } @Override public boolean supports(Class<?> authentication) { return authentication.equals(UsernamePasswordAuthenticationToken.class); }
}</pre>
注意,返回的Authentication 對象中,授權信息是空的 – 這是因為應用不同,權限信息必然也不同。
3. 安全配置——注冊認證提供者
現在認證提供者已經定義好了,我們需要在XML安全配置中指定它,使用可用的命名空間支持:
<?xml version="1.0" encoding="UTF-8"?> <beans:beans xmlns="http://www.springframework.org/schema/security http://www.springframework.org/schema/security/spring-security-3.1.xsd http://www.springframework.org/schema/beans ;<http use-expressions="true"> ... <http-basic/> </http> <authentication-manager> <authentication-provider ref="customAuthenticationProvider" /> </authentication-manager>
</beans:beans></pre>
4. 認證過程
觸發一個認證過程沒什么不同的,甚至不用定制認證提供者。我們已經用基本認證建立了我們的安全配置,所以我們可以用一個簡單的curl命令來發送一個認證請求:
curl --header "Accept:application/json" -i --user user1:user1Pass http://localhost:8080/spring-security-custom/api/foo/1之后我們從服務器獲得了期望的200成功結果:HTTP/1.1 200 OK Server: Apache-Coyote/1.1 Set-Cookie: JSESSIONID=B8F0EFA81B78DE968088EBB9AFD85A60; Path=/spring-security-custom/; HttpOnly Content-Type: application/json;charset=UTF-8 Transfer-Encoding: chunked Date: Sun, 02 Jun 2013 17:50:40 GMT5. 總結
在這篇文章中我們討論了一個為Spring安全定制的認證提供者示例。在github項目中可以找到這個實現——這是一個基本的Eclipse項目,所以你可以很輕松的導入和運行它。