如何在弹簧安全过滤器后添加自定义过滤器顺序?

时间:2016-11-07 17:51:40

标签: spring security spring-boot filter

我的过滤器如下:

@Component
@Order(1)
public class MDCFilter implements Filter {
.....

和application.properties

security.filter-order=0

在上面的设置中 - 我的过滤器首先出现,然后是安全过滤器。但是我需要在Spring安全过滤器之后使用mdcFilter。

2 个答案:

答案 0 :(得分:2)

您可以通过定义安全配置来将过滤器放在特定的spring-security过滤器旁边:

@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private MDCFilter mdcFilter;

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.addFilterBefore(mdcFilter, UsernamePasswordAuthenticationFilter.class);

    }
}

在上面的示例中,您的过滤器将在UsernamePasswordAuthenticationFilter之前。您还可以使用HttpSecurity类方法addFilterAfter(Filter filter, Class<? extends Filter> afterFilter)addFilterAt(Filter filter, Class<? extends Filter> atFilter)来指定过滤器顺序。

答案 1 :(得分:1)

如果您希望自己的过滤器使用Spring Security,您可以为Spring Security的过滤器创建自己的注册并指定顺序。

https://github.com/spring-projects/spring-boot/issues/1640

@Bean
    public FilterRegistrationBean securityFilterChain(@Qualifier(AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME) Filter securityFilter) {
        FilterRegistrationBean registration = new FilterRegistrationBean(securityFilter);
        registration.setOrder(Integer.MAX_VALUE - 1);
        registration.setName(AbstractSecurityWebApplicationInitializer.DEFAULT_FILTER_NAME);
        return registration;
    }

    @Bean
    public FilterRegistrationBean userInsertingMdcFilterRegistrationBean() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        UserInsertingMdcFilter userFilter = new UserInsertingMdcFilter();
        registrationBean.setFilter(userFilter);
        registrationBean.setOrder(Integer.MAX_VALUE);
        return registrationBean;
    }