问题描述
如何在 spring-boot 中指定过滤器的顺序?我需要在 Spring Security 过滤器之后插入我的 MDC 过滤器.我几乎尝试了所有方法,但我的过滤器始终是第一位的.这不起作用:
How can I specify order of my Filter in spring-boot? I need to insert my MDC filter after Spring Security filter. I tried almost everything but my filter was always first. This didn't work:
@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;
}
推荐答案
来自 Spring 的人再次提供帮助.见 https://github.com/spring-projects/spring-boot/issues/1640 和 https://jira.spring.io/browse/SEC-2730一个>
Guys from Spring helped again. See https://github.com/spring-projects/spring-boot/issues/1640 and https://jira.spring.io/browse/SEC-2730
Spring Security 不会在 Filter bean 上设置它的顺序创造.这意味着,当 Boot 正在创建一个FilterRegistrationBean 为它,它获取默认顺序是LOWEST_PRECEDENCE.
如果您希望自己的过滤器遵循 Spring Security,则可以为 Spring Security 的过滤器创建您自己的注册并指定订单.
If you want your own Filter to go after Spring Security's you can create your own registration for Spring Security's filter and specify the order.
所以我的问题的答案是:
So the answer to my question is:
@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;
}
这篇关于spring-boot 中的过滤顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!