UsernamePasswordAuthenticationFilter 是 AbstractAuthenticationProcessingFilter 的子類,主要作用是對用戶身份信息的驗(yàn)證。
關(guān)于 AbstractAuthenticationProcessingFilter 的分析見此: AbstractAuthenticationProcessingFilter 源碼分析。
繼承關(guān)系
UsernamePasswordAuthenticationFilter 繼承自AbstractAuthenticationProcessingFilter。
public class UsernamePasswordAuthenticationFilter extends
AbstractAuthenticationProcessingFilter {
AbstractAuthenticationProcessingFilter 是處理 form 登陸的過濾器,與 form 登陸有關(guān)的所有操作都是在該類中及其子類中進(jìn)行的。
流程分析
關(guān)于 UsernamePasswordAuthenticationFilter 處理請求的大體流程和其父類一致,見此: AbstractAuthenticationProcessingFilter 源碼分析。該處主要分析UsernamePasswordAuthenticationFilter 實(shí)現(xiàn)的父類方法 attemptAuthentication() 中的用戶身份驗(yàn)證邏輯。
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處代碼為構(gòu)建類UsernamePasswordAuthenticationToken成員變量,UsernamePasswordAuthenticationToken是一個(gè)用戶信息的載體類,用來存儲(chǔ)及傳遞用戶名和用戶密碼。 -
-->4處代碼調(diào)用getAuthenticationManager()方法獲取AuthenticationManager實(shí)例,getAuthenticationManager()方法定義如下:
protected AuthenticationManager getAuthenticationManager() {
return authenticationManager;
}
然后調(diào)用獲取到的AuthenticationManager實(shí)例的authenticate()方法對封裝在authRequest [UsernamePasswordAuthenticationToken]中的用戶名及密碼進(jìn)行驗(yàn)證。
注意:
AuthenticationManager這里可以理解為 spring security 配置文件中<authentication-manager/>的實(shí)現(xiàn)類。
附
