Spring Security 入門(四):自定義-Filter
前文導讀
本文解決問題
將自定義的 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_FILTER | ChannelProcessingFilter | http/intercept-url@requires-channel |
SECURITYCONTEXTFILTER | SecurityContextPersistenceFilter | http |
CONCURRENTSESSIONFILTER | ConcurrentSessionFilter | session-management/concurrency-control |
HEADERS_FILTER | HeaderWriterFilter | http/headers |
CSRF_FILTER | CsrfFilter | http/csrf |
LOGOUT_FILTER | LogoutFilter | http/logout |
X509_FILTER | X509AuthenticationFilter | http/x509 |
PREAUTHFILTER | AbstractPreAuthenticatedProcessingFilter( Subclasses) | N/A |
CAS_FILTER | CasAuthenticationFilter | N/A |
FORMLOGINFILTER | UsernamePasswordAuthenticationFilter | http/form-login |
BASICAUTHFILTER | BasicAuthenticationFilter | http/http-basic |
SERVLETAPISUPPORT_FILTER | SecurityContextHolderAwareRequestFilter | http/@servlet-api-provision |
JAASAPISUPPORT_FILTER | JaasApiIntegrationFilter | http/@jaas-api-provision |
REMEMBERMEFILTER | RememberMeAuthenticationFilter | http/remember-me |
ANONYMOUS_FILTER | AnonymousAuthenticationFilter | http/anonymous |
SESSIONMANAGEMENTFILTER | SessionManagementFilter | session-management |
EXCEPTIONTRANSLATIONFILTER | ExceptionTranslationFilter | http |
FILTERSECURITYINTERCEPTOR | FilterSecurityInterceptor | http |
SWITCHUSERFILTER | SwitchUserFilter | N/A |
過濾器順序從上到下
自定義 Filter
自定義的 Filter
建議繼承 GenericFilterBean
,本文示例:
publicclassBeforeLoginFilterextendsGenericFilterBean{
@Override
publicvoid doFilter(ServletRequest servletRequest,ServletResponse servletResponse,FilterChain filterChain)throwsIOException,ServletException{
System.out.println("This is a filter before UsernamePasswordAuthenticationFilter.");
// 繼續呼叫 Filter 鏈
filterChain.doFilter(servletRequest, servletResponse);
}
}
配置自定義 Filter 在 Spring Security 過濾器鏈中的位置
配置很簡單,本文示例:
protectedvoid configure(HttpSecurity http)throwsException{
http
.authorizeRequests()
.antMatchers("/").permitAll()
.antMatchers("/user/**").hasRole("USER")
.and()
.formLogin().loginPage("/login").defaultSuccessUrl("/user")
.and()
.logout().logoutUrl("/logout").logoutSuccessUrl("/login");
// 在 UsernamePasswordAuthenticationFilter 前新增 BeforeLoginFilter
http.addFilterBefore(newBeforeLoginFilter(),UsernamePasswordAuthenticationFilter.class);
// 在 CsrfFilter 後新增 AfterCsrfFilter
http.addFilterAfter(newAfterCsrfFilter(),CsrfFilter.class);
}
說明: HttpSecurity
有三個常用方法來配置:
addFilterBefore(Filter filter, Class beforeFilter) 在 beforeFilter 之前新增 filter
addFilterAfter(Filter filter, Class afterFilter) 在 afterFilter 之後新增 filter
addFilterAt(Filter filter, Class atFilter) 在 atFilter 相同位置新增 filter, 此 filter 不覆蓋 filter
通過在不同
Filter
的doFilter()
方法中加斷點除錯,可以判斷哪個 filter 先執行,從而判斷 filter 的執行順序 。