1. 程式人生 > >Spring Security 入門(四):自定義-Filter

Spring Security 入門(四):自定義-Filter

前文導讀

?wx_fmt=png&wxfrom=5&wx_lazy=1

本文解決問題

將自定義的 Filter 加入到 Spring Security 中的 Filter 鏈中的指定位置。

Spring Security 預設的過濾器鏈

官網位置:http://docs.spring.io/spring-security/site/docs/5.0.0.M1/reference/htmlsingle/#ns-custom-filters

別名類名稱Namespace Element or Attribute
CHANNEL_FILTERChannelProcessingFilterhttp/intercept-url@requires-channel
SECURITYCONTEXTFILTERSecurityContextPersistenceFilterhttp
CONCURRENTSESSIONFILTERConcurrentSessionFiltersession-management/concurrency-control
HEADERS_FILTERHeaderWriterFilterhttp/headers
CSRF_FILTERCsrfFilterhttp/csrf
LOGOUT_FILTERLogoutFilterhttp/logout
X509_FILTERX509AuthenticationFilterhttp/x509
PREAUTHFILTERAbstractPreAuthenticatedProcessingFilter( Subclasses)N/A
CAS_FILTERCasAuthenticationFilterN/A
FORMLOGINFILTERUsernamePasswordAuthenticationFilterhttp/form-login
BASICAUTHFILTERBasicAuthenticationFilterhttp/http-basic
SERVLETAPISUPPORT_FILTERSecurityContextHolderAwareRequestFilterhttp/@servlet-api-provision
JAASAPISUPPORT_FILTERJaasApiIntegrationFilterhttp/@jaas-api-provision
REMEMBERMEFILTERRememberMeAuthenticationFilterhttp/remember-me
ANONYMOUS_FILTERAnonymousAuthenticationFilterhttp/anonymous
SESSIONMANAGEMENTFILTERSessionManagementFiltersession-management
EXCEPTIONTRANSLATIONFILTERExceptionTranslationFilterhttp
FILTERSECURITYINTERCEPTORFilterSecurityInterceptorhttp
SWITCHUSERFILTERSwitchUserFilterN/A

過濾器順序從上到下

自定義 Filter

自定義的 Filter 建議繼承 GenericFilterBean,本文示例:

  1. publicclassBeforeLoginFilterextendsGenericFilterBean{

  2. @Override

  3. publicvoid doFilter(ServletRequest servletRequest,ServletResponse servletResponse,FilterChain filterChain)throwsIOException,ServletException{

  4. System.out.println("This is a filter before UsernamePasswordAuthenticationFilter.");

  5. // 繼續呼叫 Filter 鏈

  6.        filterChain.doFilter(servletRequest, servletResponse);

  7. }

  8. }

配置自定義 Filter 在 Spring Security 過濾器鏈中的位置

配置很簡單,本文示例:

  1. protectedvoid configure(HttpSecurity http)throwsException{

  2.        http

  3. .authorizeRequests()

  4. .antMatchers("/").permitAll()

  5. .antMatchers("/user/**").hasRole("USER")

  6. .and()

  7. .formLogin().loginPage("/login").defaultSuccessUrl("/user")

  8. .and()

  9. .logout().logoutUrl("/logout").logoutSuccessUrl("/login");

  10. // 在 UsernamePasswordAuthenticationFilter 前新增 BeforeLoginFilter

  11.        http.addFilterBefore(newBeforeLoginFilter(),UsernamePasswordAuthenticationFilter.class);

  12. // 在 CsrfFilter 後新增 AfterCsrfFilter

  13.        http.addFilterAfter(newAfterCsrfFilter(),CsrfFilter.class);

  14. }

說明: HttpSecurity 有三個常用方法來配置:

  • addFilterBefore(Filter filter, Class beforeFilter) 在 beforeFilter 之前新增 filter

  • addFilterAfter(Filter filter, Class afterFilter) 在 afterFilter 之後新增 filter

  • addFilterAt(Filter filter, Class atFilter) 在 atFilter 相同位置新增 filter, 此 filter 不覆蓋 filter

通過在不同 FilterdoFilter() 方法中加斷點除錯,可以判斷哪個 filter 先執行,從而判斷 filter 的執行順序 。

推薦閱讀