防止 Spring Boot 注册 servlet 过滤器 [英] Prevent Spring Boot from registering a servlet filter
问题描述
我有一个 Spring Boot WebMVC 应用程序和一个继承自 AbstractPreAuthenticatedProcessingFilter 的 bean,我将其显式添加到 Spring Security 过滤器链中的特定位置.我的 Spring Security 配置如下所示:
I have a Spring Boot WebMVC application, and a bean that inherits from AbstractPreAuthenticatedProcessingFilter which I am explicitly adding to a specific spot in the Spring Security filter chain. My Spring Security configuration looks like this:
<http pattern="/rest/**">
<intercept-url pattern="/**" access="ROLE_USER"/>
<http-basic/>
<custom-filter after="BASIC_AUTH_FILTER" ref="preAuthenticationFilter"/>
</http>
<beans:bean id="preAuthenticationFilter" class="a.b.PreAuthenticationFilter">
<beans:property name="authenticationManager" ref="customAuthenticationManager"/>
</beans:bean>
安全配置有效.问题是,由于 PreAuthenticationFilter 类继承自 AbstractPreAuthenticatedProcessingFilter,Spring Boot 将其视为通用 servlet 过滤器,并将其添加到所有请求的 servlet 过滤器链中.我不希望此过滤器成为所有请求的过滤器链的一部分.我只希望它成为我配置的特定 Spring Security 过滤器链的一部分.有没有办法防止 Spring Boot 自动将 preAuthenticationFilter bean 添加到过滤器链中?
The security configuration works. The problem is, because the PreAuthenticationFilter class inherits from AbstractPreAuthenticatedProcessingFilter, Spring Boot treats it as a general purpose servlet filter and is adding it to the servlet filter chain for all requests. I don't want this filter to be part of the filter chain for all requests. I only want it to be part of the specific Spring Security filter chain that I've configured. Is there a way to prevent Spring Boot from automatically adding the preAuthenticationFilter bean to the filter chain?
推荐答案
默认情况下,Spring Boot 会为应用程序上下文中的每个 Filter
创建一个 FilterRegistrationBean
>FilterRegistrationBean 不存在.这允许您通过为 Filter
声明您自己的 FilterRegistrationBean
来控制注册过程,包括禁用注册.对于您的 PreAuthenticationFilter
,所需的配置如下所示:
By default Spring Boot creates a FilterRegistrationBean
for every Filter
in the application context for which a FilterRegistrationBean
doesn't already exist. This allows you to take control of the registration process, including disabling registration, by declaring your own FilterRegistrationBean
for the Filter
. For your PreAuthenticationFilter
the required configuration would look like this:
@Bean
public FilterRegistrationBean registration(PreAuthenticationFilter filter) {
FilterRegistrationBean registration = new FilterRegistrationBean(filter);
registration.setEnabled(false);
return registration;
}
您可能还对 这个 Spring Boot 问题感兴趣,它讨论了如何禁用Filter
和Servlet
bean的自动注册.
You may also be interested in this Spring Boot issue which discusses how to disable the automatic registration of Filter
and Servlet
beans.
这篇关于防止 Spring Boot 注册 servlet 过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!