四、Spring Security之默认的过滤器链及自定义Filter

    xiaoxiao2025-04-23  21

    别名类名称Namespace Element or AttributeCHANNEL_FILTERChannelProcessingFilterhttp/intercept-url@requires-channelSECURITY_CONTEXT_FILTERSecurityContextPersistenceFilterhttpCONCURRENT_SESSION_FILTERConcurrentSessionFiltersession-management/concurrency-controlHEADERS_FILTERHeaderWriterFilterhttp/headersCSRF_FILTERCsrfFilterhttp/csrfLOGOUT_FILTERLogoutFilterhttp/logoutX509_FILTERX509AuthenticationFilterhttp/x509PRE_AUTH_FILTERAbstractPreAuthenticatedProcessingFilter( Subclasses)N/ACAS_FILTERCasAuthenticationFilterN/AFORM_LOGIN_FILTERUsernamePasswordAuthenticationFilterhttp/form-loginBASIC_AUTH_FILTERBasicAuthenticationFilterhttp/http-basicSERVLET_API_SUPPORT_FILTERSecurityContextHolderAwareRequestFilterhttp/@servlet-api-provisionJAAS_API_SUPPORT_FILTERJaasApiIntegrationFilterhttp/@jaas-api-provisionREMEMBER_ME_FILTERRememberMeAuthenticationFilterhttp/remember-meANONYMOUS_FILTERAnonymousAuthenticationFilterhttp/anonymousSESSION_MANAGEMENT_FILTERSessionManagementFiltersession-managementEXCEPTION_TRANSLATION_FILTERExceptionTranslationFilterhttpFILTER_SECURITY_INTERCEPTORFilterSecurityInterceptorhttpSWITCH_USER_FILTERSwitchUserFilterN/A

    过滤器顺序从上到下

    自定义 Filter 自定义的 Filter 建议继承 GenericFilterBean,本文示例:

    package com.example.filter; import org.springframework.web.filter.GenericFilterBean; import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.ServletRequest; import javax.servlet.ServletResponse; import java.io.IOException; /** * @author 咸鱼 * @date 2019-05-26 18:02 */ public class BeforeLoginFilter extends GenericFilterBean { @Override public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("在 UsernamePasswordAuthenticationFilter 前调用"); chain.doFilter(request, response); } }

    配置自定义 Filter 在 Spring Security 过滤器链中的位置 配置很简单,本文示例:

    @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() .antMatchers("/").permitAll() .antMatchers("/user/**").hasAuthority("USER") .and() .formLogin().loginPage("/login").defaultSuccessUrl("/user") .and() .logout().logoutUrl("/logout").logoutSuccessUrl("/login"); // 在 UsernamePasswordAuthenticationFilter 前添加 BeforeLoginFilter http.addFilterBefore(new BeforeLoginFilter(), UsernamePasswordAuthenticationFilter.class); // 在 CsrfFilter 后添加 AfterCsrfFilter http.addFilterAfter(new AfterCsrfFilter(), CsrfFilter.class); }

    说明: HttpSecurity 有三个常用方法来配置:

    addFilterBefore(Filter filter, Class<? extends Filter> beforeFilter) 在 beforeFilter 之前添加 filteraddFilterAfter(Filter filter, Class<? extends Filter> afterFilter) 在 afterFilter 之后添加 filteraddFilterAt(Filter filter, Class<? extends Filter> atFilter) 在 atFilter 相同位置添加 filter, 此 filter 不覆盖 filter

    通过在不同 Filter 的 doFilter() 方法中加断点调试,可以判断哪个 filter 先执行,从而判断 filter 的执行顺序 。

    最新回复(0)