SpringSecurity過濾器介紹


常用過濾器

  1. org.springframework.security.web.context.SecurityContextPersistenceFilter

首當其沖的一個過濾器,作用之重要,自不必多言。
SecurityContextPersistenceFilter主要是使用SecurityContextRepository在session中保存或更新一個
SecurityContext,並將SecurityContext給以后的過濾器使用,來為后續filter建立所需的上下文。
SecurityContext中存儲了當前用戶的認證以及權限信息。

  1. org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter

此過濾器用於集成SecurityContext到Spring異步執行機制中的WebAsyncManager

  1. org.springframework.security.web.header.HeaderWriterFilter

向請求的Header中添加相應的信息,可在http標簽內部使用security:headers來控制

  1. org.springframework.security.web.csrf.CsrfFilter

csrf又稱跨域請求偽造,SpringSecurity會對所有post請求驗證是否包含系統生成的csrf的token信息,
如果不包含,則報錯。起到防止csrf攻擊的效果。

  1. org.springframework.security.web.authentication.logout.LogoutFilter

匹配URL為/logout的請求,實現用戶退出,清除認證信息。

  1. org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter

認證操作全靠這個過濾器,默認匹配URL為/login且必須為POST請求。

  1. org.springframework.security.web.authentication.ui.DefaultLoginPageGeneratingFilter

如果沒有在配置文件中指定認證頁面,則由該過濾器生成一個默認認證頁面。

  1. org.springframework.security.web.authentication.ui.DefaultLogoutPageGeneratingFilter

由此過濾器可以生產一個默認的退出登錄頁面

  1. org.springframework.security.web.authentication.www.BasicAuthenticationFilter

此過濾器會自動解析HTTP請求中頭部名字為Authentication,且以Basic開頭的頭信息。

  1. org.springframework.security.web.savedrequest.RequestCacheAwareFilter

通過HttpSessionRequestCache內部維護了一個RequestCache,用於緩存HttpServletRequest

  1. org.springframework.security.web.servletapi.SecurityContextHolderAwareRequestFilter

針對ServletRequest進行了一次包裝,使得request具有更加豐富的API

  1. org.springframework.security.web.authentication.AnonymousAuthenticationFilter

當SecurityContextHolder中認證信息為空,則會創建一個匿名用戶存入到SecurityContextHolder中。
spring security為了兼容未登錄的訪問,也走了一套認證流程,只不過是一個匿名的身份。

  1. org.springframework.security.web.session.SessionManagementFilter

SecurityContextRepository限制同一用戶開啟多個會話的數量

  1. org.springframework.security.web.access.ExceptionTranslationFilter

異常轉換過濾器位於整個springSecurityFilterChain的后方,用來轉換整個鏈路中出現的異常

  1. org.springframework.security.web.access.intercept.FilterSecurityInterceptor

獲取所配置資源訪問的授權信息,根據SecurityContextHolder中存儲的用戶信息來決定其是否有權
限。

DelegatingFilterProxy

我們在web.xml中配置了一個名稱為springSecurityFilterChain的過濾器DelegatingFilterProxy,接下直接對
DelegatingFilterProxy源碼里重要代碼進行說明,其中刪減掉了一些不重要的代碼。

public class DelegatingFilterProxy extends GenericFilterBean {
    @Nullable
    private String contextAttribute;
    @Nullable
    private WebApplicationContext webApplicationContext;
    @Nullable
    private String targetBeanName;
    private boolean targetFilterLifecycle;
    @Nullable
    private volatile Filter delegate;  //注:這個過濾器才是真正加載的過濾器
    private final Object delegateMonitor;

    //注:doFilter才是過濾器的入口,直接從這看!
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        Filter delegateToUse = this.delegate;
        if (delegateToUse == null) {
            synchronized (this.delegateMonitor) {
                delegateToUse = this.delegate;
                if (delegateToUse == null) {
                    WebApplicationContext wac = this.findWebApplicationContext();
                    if (wac == null) {
                        throw new IllegalStateException("No WebApplicationContext found: no ContextLoaderListener or DispatcherServlet registered?");
                    }
                    //第一步:doFilter中最重要的一步,初始化上面私有過濾器屬性delegate
                    delegateToUse = this.initDelegate(wac);
                }
                this.delegate = delegateToUse;
            }
        }
        //第三步:執行FilterChainProxy過濾器
        this.invokeDelegate(delegateToUse, request, response, filterChain);
    }

    //第二步:直接看最終加載的過濾器到底是誰
    protected Filter initDelegate(WebApplicationContext wac) throws ServletException {
        //debug得知targetBeanName為:springSecurityFilterChain
        String targetBeanName = this.getTargetBeanName();
        Assert.state(targetBeanName != null, "No target bean name set");
        //debug得知delegate對象為:FilterChainProxy
        Filter delegate = (Filter) wac.getBean(targetBeanName, Filter.class);
        if (this.isTargetFilterLifecycle()) {
            delegate.init(this.getFilterConfig());
        }
        return delegate;
    }

    protected void invokeDelegate(Filter delegate, ServletRequest request, ServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        delegate.doFilter(request, response, filterChain);
    }
}

由此可知,DelegatingFilterProxy通過springSecurityFilterChain這個名稱,得到了一個FilterChainProxy過濾器,
最終在第三步執行了這個過濾器。

FilterChainProxy

public class FilterChainProxy extends GenericFilterBean {
    private static final Log logger = LogFactory.getLog(FilterChainProxy.class);
    private static final String FILTER_APPLIED = FilterChainProxy.class.getName().concat(".APPLIED");
    private List<SecurityFilterChain> filterChains;
    private FilterChainProxy.FilterChainValidator filterChainValidator;
    private HttpFirewall firewall;

    // 可以通過一個叫SecurityFilterChain的對象實例化出一個FilterChainProxy對象
    // 這FilterChainProxy又是何方神聖?會不會是真正的過濾器鏈對象呢?先留着這個疑問!
    public FilterChainProxy(SecurityFilterChain chain) {
        this(Arrays.asList(chain));
    }

    //又是SecurityFilterChain這家伙!嫌疑更大了!
    public FilterChainProxy(List<SecurityFilterChain> filterChains) {
        this.filterChainValidator = new FilterChainProxy.NullFilterChainValidator();
        this.firewall = new StrictHttpFirewall();
        this.filterChains = filterChains;
    }

    //注:直接從doFilter看
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        boolean clearContext = request.getAttribute(FILTER_APPLIED) == null;
        if (clearContext) {
            try {
                request.setAttribute(FILTER_APPLIED, Boolean.TRUE);
                this.doFilterInternal(request, response, chain);
            } finally {
                SecurityContextHolder.clearContext();
                request.removeAttribute(FILTER_APPLIED);
            }
        } else {
            //第一步:具體操作調用下面的doFilterInternal方法了
            this.doFilterInternal(request, response, chain);
        }
    }

    private void doFilterInternal(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        FirewalledRequest fwRequest = this.firewall.getFirewalledRequest((HttpServletRequest) request);
        HttpServletResponse fwResponse = this.firewall.getFirewalledResponse((HttpServletResponse) response);
        //第二步:封裝要執行的過濾器鏈,那么多過濾器就在這里被封裝進去了!
        List<Filter> filters = this.getFilters((HttpServletRequest) fwRequest);
        if (filters != null && filters.size() != 0) {
            FilterChainProxy.VirtualFilterChain vfc = new FilterChainProxy.VirtualFilterChain(fwRequest, chain, filters);
            //第四步:加載過濾器鏈
            vfc.doFilter(fwRequest, fwResponse);
        } else {
            if (logger.isDebugEnabled()) {
                logger.debug(UrlUtils.buildRequestUrl(fwRequest) + (filters == null ? " has no matching filters" : " has an empty filter list"));
            }
            fwRequest.reset();
            chain.doFilter(fwRequest, fwResponse);
        }
    }

    private List<Filter> getFilters(HttpServletRequest request) {
        Iterator var2 = this.filterChains.iterator();
        //第三步:封裝過濾器鏈到SecurityFilterChain中!
        SecurityFilterChain chain;
        do {
            if (!var2.hasNext()) {
                return null;
            }
            chain = (SecurityFilterChain) var2.next();
        } while (!chain.matches(request));
        return chain.getFilters();
    }
}

看完上面的代碼,原來這些過濾器都被封裝進SecurityFilterChain中了。

SecurityFilterChain

最后看SecurityFilterChain,這是個接口,實現類也只有一個,這才是web.xml中配置的過濾器鏈對象!

//接口 
public interface SecurityFilterChain {
    boolean matches(HttpServletRequest var1);

    List<Filter> getFilters();
}

//實現類 
public final class DefaultSecurityFilterChain implements SecurityFilterChain {
    private static final Log logger = LogFactory.getLog(DefaultSecurityFilterChain.class);
    private final RequestMatcher requestMatcher;
    private final List<Filter> filters;

    public DefaultSecurityFilterChain(RequestMatcher requestMatcher, Filter... filters) {
        this(requestMatcher, Arrays.asList(filters));
    }

    public DefaultSecurityFilterChain(RequestMatcher requestMatcher, List<Filter> filters) {
        logger.info("Creating filter chain: " + requestMatcher + ", " + filters);
        this.requestMatcher = requestMatcher;
        this.filters = new ArrayList(filters);
    }

    public RequestMatcher getRequestMatcher() {
        return this.requestMatcher;
    }

    public List<Filter> getFilters() {
        return this.filters;
    }

    public boolean matches(HttpServletRequest request) {
        return this.requestMatcher.matches(request);
    }

    public String toString() {
        return "[ " + this.requestMatcher + ", " + this.filters + "]";
    }
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM