一尘不染

spring启动时的过滤顺序

spring-mvc

如何在spring-boot中指定我的过滤器的顺序?我需要在Spring
Security过滤器之后插入我的MDC过滤器。我几乎尝试了所有方法,但过滤器始终是第一位的。这不起作用:

@Bean
@Order(Ordered.LOWEST_PRECEDENCE)
public UserInsertingMdcFilter userInsertingMdcFilter() {
    return new UserInsertingMdcFilter();
}

这也不起作用:

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

阅读 525

收藏
2020-06-01

共1个答案

一尘不染

spring的家伙再次提供帮助。参见https://github.com/spring-projects/spring-
boot/issues/1640和https://jira.spring.io/browse/SEC-2730

Spring Security不会在它创建的Filter
bean上设置订单。这意味着,在Boot为它创建FilterRegistrationBean时,它将获得默认顺序LOWEST_PRECEDENCE。

如果您想在Spring Security之后使用自己的过滤器,则可以为Spring Security的过滤器创建自己的注册并指定顺序。

所以我的问题的答案是:

@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;
}
2020-06-01