UsernamePasswordAuthenticationFilter
是 AbstractAuthenticationProcessingFilter
的子類,主要作用是對用戶身份信息的驗證。
關於 AbstractAuthenticationProcessingFilter
的分析見此: AbstractAuthenticationProcessingFilter 源碼分析。
繼承關係
UsernamePasswordAuthenticationFilter
繼承自AbstractAuthenticationProcessingFilter
。
public class UsernamePasswordAuthenticationFilter extends
AbstractAuthenticationProcessingFilter {
AbstractAuthenticationProcessingFilter
是處理 form 登陸的過濾器,與 form 登陸有關的所有操作都是在該類中及其子類中進行的。
流程分析
關於 UsernamePasswordAuthenticationFilter
處理請求的大體流程和其父類一致,見此: AbstractAuthenticationProcessingFilter 源碼分析。該處主要分析UsernamePasswordAuthenticationFilter
實現的父類方法 attemptAuthentication()
中的用戶身份驗證邏輯。
attemptAuthentication()
方法代碼如下所示:
public Authentication attemptAuthentication(HttpServletRequest request,
HttpServletResponse response) throws AuthenticationException {
if (postOnly && !request.getMethod().equals("POST")) {
throw new AuthenticationServiceException(
"Authentication method not supported: " + request.getMethod());
}
-->1 String username = obtainUsername(request);
-->2 String password = obtainPassword(request);
if (username == null) {
username = "";
}
if (password == null) {
password = "";
}
username = username.trim();
-->3 UsernamePasswordAuthenticationToken authRequest = new UsernamePasswordAuthenticationToken(
username, password);
// Allow subclasses to set the "details" property
setDetails(request, authRequest);
-->4 return this.getAuthenticationManager().authenticate(authRequest);
}
-->1
和-->2
處的代碼從request
中提取用戶名和密碼。-->3
處代碼爲構建類UsernamePasswordAuthenticationToken
成員變量,UsernamePasswordAuthenticationToken
是一個用戶信息的載體類,用來存儲及傳遞用戶名和用戶密碼。-->4
處代碼調用getAuthenticationManager()
方法獲取AuthenticationManager
實例,getAuthenticationManager()
方法定義如下:
protected AuthenticationManager getAuthenticationManager() {
return authenticationManager;
}
然後調用獲取到的AuthenticationManager
實例的authenticate()
方法對封裝在authRequest [UsernamePasswordAuthenticationToken]
中的用戶名及密碼進行驗證。
注意:
AuthenticationManager
這裏可以理解爲 spring security 配置文件中<authentication-manager/>
的實現類。
附
attemptAuthentication 驗證函數流程圖.png