Spring Security添加自定义Filter
2019-11-06 本文已影响0人
Real_man
Spring Security默认维护了一个Filter Chain来实现其功能,但是有时候我们想要在过滤器链中添加自己的Filter,但是Spring Security的Filter Chain并没有直接暴露出来,要如何处理呢?
首先看一下Spring 默认的Filter,如下的Filter是按照在Filter Chain排序好的方式出现的。
别名 | Filter Class | Namespace Element or Attribute |
---|---|---|
CHANNEL_FILTER | ChannelProcessingFilter |
http/intercept-url@requires-channel |
SECURITY_CONTEXT_FILTER | SecurityContextPersistenceFilter |
http |
CONCURRENT_SESSION_FILTER | 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 |
PRE_AUTH_FILTER |
AbstractPreAuthenticatedProcessingFilter Subclasses |
N/A |
CAS_FILTER | CasAuthenticationFilter |
N/A |
FORM_LOGIN_FILTER | UsernamePasswordAuthenticationFilter |
http/form-login |
BASIC_AUTH_FILTER | BasicAuthenticationFilter |
http/http-basic |
SERVLET_API_SUPPORT_FILTER | SecurityContextHolderAwareRequestFilter |
http/@servlet-api-provision |
JAAS_API_SUPPORT_FILTER | JaasApiIntegrationFilter |
http/@jaas-api-provision |
REMEMBER_ME_FILTER | RememberMeAuthenticationFilter |
http/remember-me |
ANONYMOUS_FILTER | AnonymousAuthenticationFilter |
http/anonymous |
SESSION_MANAGEMENT_FILTER | SessionManagementFilter |
session-management |
EXCEPTION_TRANSLATION_FILTER | ExceptionTranslationFilter |
http |
FILTER_SECURITY_INTERCEPTOR | FilterSecurityInterceptor |
http |
SWITCH_USER_FILTER | SwitchUserFilter |
N/A |
添加自定义的Filter:
- addFilterAfter class参数必须上面已知的Filter或者已经添加到内部的新的Filter
- addFilterBefore class参数必须上面已知的Filter或者已经添加到内部的新的Filter
- addFilter 必须是上面表格中的一种Filter
参考上次Spring Security的介绍:https://www.jianshu.com/p/efd135315401
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/css/**", "/index").permitAll()
.antMatchers("/user/**").hasRole("USER")
.and()
.formLogin().loginPage("/login").failureUrl("/login-error");
// 添加自定义Filter
http.addFilterAfter(new MyFilter(), UsernamePasswordAuthenticationFilter.class);
}
}
// 自定义Filter
public class MyFilter implements Filter {
Logger log = LoggerFactory.getLogger(getClass());
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
log.info("custom filter begin to work");
}
@Override
public void destroy() {
}
}
image-20191106071417244
End
Spring Security内部细节比较多,让自己有个印象。
参考:https://docs.spring.io/spring-security/site/docs/5.1.7.RELEASE/reference/htmlsingle/#cas-sample