精彩文章免费看

Spring Security添加自定义Filter

Spring Security默认维护了一个Filter Chain来实现其功能,但是有时候我们想要在过滤器链中添加自己的Filter,但是Spring Security的Filter Chain并没有直接暴露出来,要如何处理呢?

首先看一下Spring 默认的Filter,如下的Filter是按照在Filter Chain排序好的方式出现的。

Filter Class Namespace Element or Attribute 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 FILTER_SECURITY_INTERCEPTOR FilterSecurityInterceptor SWITCH_USER_FILTER SwitchUserFilter

添加自定义的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 {
                    .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() {
    

    Spring Security内部细节比较多,让自己有个印象。

    参考:https://docs.spring.io/spring-security/site/docs/5.1.7.RELEASE/reference/htmlsingle/#cas-sample

  •