弹簧启动中的过滤器顺序

2022-08-31 14:01:41

如何指定过滤器在弹簧启动中的顺序?我需要在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;
}

答案 1

来自春天的家伙们再次帮助了我。查看 https://github.com/spring-projects/spring-boot/issues/1640https://jira.spring.io/browse/SEC-2730

Spring Security不会在其创建的过滤器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;
}

答案 2

此问题已在 Spring Boot 1.2 中修复。安全链现在默认为 顺序 。0

它也可以通过属性进行设置:

security.filter-order=0 # Security filter chain order.

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


推荐