使用WebSecurityConfigurerAdapter而不是WebMvcConfigurerAdapter添加HandlerInterceptor

时间:2016-08-19 16:46:30

标签: java spring spring-mvc spring-security spring-boot

我的应用程序有以下配置:

@EnableTransactionManagement
@EnableWebSecurity
public class SecurityApiConfiguration
  extends WebSecurityConfigurerAdapter {
  ...
}

我想添加HandlerInterceptorAdapter。可以使用WebSecurityConfigurerAdapter吗?我只是看到使用WebMvcConfigurerAdapter的示例。

1 个答案:

答案 0 :(得分:0)

我在Spring-boot 2.0中也遇到了同样的问题,因为它本身不支持名称的原因是HandleInterceptor,总是与WebMVCConfigurationAdpater相关联。另一方面,由于我们在WebSecurityConfigureAdapter中具有扩展支持过滤器,因此我们使用了OncePerRequestFilter

public class SampleInterceptorFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        //Your custom logic
       }

   }


    @Bean
    public SampleInterceptorFilter sampleInterceptorFilter() {
        return new SampleInterceptorFilter();
    }

    @Bean
    protected FilterRegistrationBean sampleInterceptorFilterRegistor() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(sampleInterceptorFilter()());
        bean.setName("SOME_NAME_FILTER");
        bean.setEnabled(false);
        return bean;
    }


    @Override
    protected void configure(final HttpSecurity http) throws Exception {
        http.csrf().disable();

        //Here we need to configure accordingly order of filter plays vital role
        http.addFilterAfter(cyzfilter(), ExceptionTranslationFilter.class).addFilterAfter(xyzFilter(),
                ServiceUserPreAuthFilter.class).addFilterBefore(SampleInterceptorFilter(), ServiceUserPreAuthFilter.class);

    }