天天看點

SpringSecurity認證流程分析

我們前面實作了使用自定義認證界面的功能,但是背景認證校驗還是使用的’/login’來處理的,對比的賬号密碼還是我們寫在記憶體的資料,那我們如果想要實作和資料庫中的資料比較,那麼我們就必須要實作自定義認證邏輯的實作,本文我們就先來分析下系統自帶的認證是怎麼走的。

一、UsernamePasswordAuthenticationFilter

 系統認證是通過UsernamePasswordAuthenticationFilter 過濾器實作的,是以我們需要來分析下這個過濾器的源碼

1.表單送出參數

SpringSecurity認證流程分析

2.doFilter方法

 因為UsernamePasswordAuthenticationFilter就是一個過濾器,是以我們要分析他的原理,肯定需要通過doFilter方法來開始,注意該方法在父類中。

SpringSecurity認證流程分析

public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)res;
        if (!this.requiresAuthentication(request, response)) {
            chain.doFilter(request, response);
        } else {
            if (this.logger.isDebugEnabled()) {
                this.logger.debug("Request is to process authentication");
            }

            Authentication authResult;
            try {
                authResult = this.attemptAuthentication(request, response);
                if (authResult == null) {
                    return;
                }

                this.sessionStrategy.onAuthentication(authResult, request, response);
            } catch (InternalAuthenticationServiceException var8) {
                this.logger.error("An internal error occurred while trying to authenticate the user.", var8);
                this.unsuccessfulAuthentication(request, response, var8);
                return;
            } catch (AuthenticationException var9) {
                this.unsuccessfulAuthentication(request, response, var9);
                return;
            }

            if (this.continueChainBeforeSuccessfulAuthentication) {
                chain.doFilter(request, response);
            }

            this.successfulAuthentication(request, response, chain, authResult);
        }
    }      
SpringSecurity認證流程分析
SpringSecurity認證流程分析

通過上面我們發現,要檢視認證的流程我們需要進入attemptAuthentication方法中檢視

3.認證的過程

SpringSecurity認證流程分析

進入this.getAuthenticationManager().authenticate(authRequest);中

SpringSecurity認證流程分析
SpringSecurity認證流程分析
SpringSecurity認證流程分析
SpringSecurity認證流程分析
SpringSecurity認證流程分析
SpringSecurity認證流程分析
SpringSecurity認證流程分析
SpringSecurity認證流程分析
SpringSecurity認證流程分析
SpringSecurity認證流程分析
SpringSecurity認證流程分析

 我們發現最終去做認證的是 UserDetailsService接口的實作去完成的,那麼我們要自定義認證過程,那麼也隻需要實作該接口接口,下篇我們具體看看如何實作。