Spring Security过滤器链对forward转发请求不生效如何解决
问题原因
- Spring Security过滤器链默认仅处理
DispatcherType.REQUEST类型的原生请求,forward产生的DispatcherType.FORWARD类型请求默认不会被Spring Security过滤器拦截,因此/view绑定的安全规则不会在forward后生效。 - 你当前配置的RouteFilter优先级为-100,和Spring Security过滤器链默认优先级相同,且你将其配置为在FilterChainProxy之前执行,导致不带ACTION参数的/api请求还未经过Spring Security校验就被提前转发,安全规则根本没有触发机会。
- 你现有的安全配置对所有/api请求统一要求OAuth权限,即便调整了forward规则,不带ACTION参数的/api请求也会在进入过滤器前就被OAuth校验拦截,无法走到转发逻辑。
修复步骤
- 配置Spring Security支持处理FORWARD请求
在application.properties中添加如下配置即可:
spring.security.filter.dispatcher-types=request,forward
如果使用代码配置,可手动调整Spring Security过滤器的分派类型:
import org.springframework.boot.web.servlet.FilterRegistrationBean; import org.springframework.context.annotation.Bean; import org.springframework.security.web.FilterChainProxy; import javax.servlet.DispatcherType; @Bean public FilterRegistrationBean<FilterChainProxy> securityFilterRegistration(FilterChainProxy springSecurityFilterChain) { FilterRegistrationBean<FilterChainProxy> registration = new FilterRegistrationBean<>(springSecurityFilterChain); registration.setDispatcherTypes(DispatcherType.REQUEST, DispatcherType.FORWARD); registration.setOrder(-100); return registration; }
- 调整安全配置的匹配规则
修改第一套OAuth安全配置,仅对携带ACTION=INIT/ACTION=FETCH参数的/api请求要求OAuth权限:
@Configuration @Order(1) public class Config extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests() // 仅带指定ACTION参数的/api请求需要OAuth权限 .antMatchers("/api").params("ACTION", "INIT", "FETCH") .hasAuthority("SCOPE_API") .anyRequest() .authenticated() .and() .oauth2ResourceServer() .opaqueToken(); } }
- 修正代码笔误
你Controller中/view接口的注解参数拼写错误,param需要改为params:
// 修正前 @PostMapping(path="/view", param = "!ACTION") // 修正后 @PostMapping(path="/view", params = "!ACTION")
内容的提问来源于stack exchange,提问作者Mohit Shrivastava
相关产品推荐
相关产品推荐

