You need to enable JavaScript to run this app. Spring Security过滤器链对forward转发请求不生效如何解决
优惠活动
大模型
产品
解决方案
定价
更多

Spring Security过滤器链对forward转发请求不生效如何解决

问题原因

  1. Spring Security过滤器链默认仅处理DispatcherType.REQUEST类型的原生请求,forward产生的DispatcherType.FORWARD类型请求默认不会被Spring Security过滤器拦截,因此/view绑定的安全规则不会在forward后生效。
  2. 你当前配置的RouteFilter优先级为-100,和Spring Security过滤器链默认优先级相同,且你将其配置为在FilterChainProxy之前执行,导致不带ACTION参数的/api请求还未经过Spring Security校验就被提前转发,安全规则根本没有触发机会。
  3. 你现有的安全配置对所有/api请求统一要求OAuth权限,即便调整了forward规则,不带ACTION参数的/api请求也会在进入过滤器前就被OAuth校验拦截,无法走到转发逻辑。

修复步骤

  1. 配置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;
}
  1. 调整安全配置的匹配规则
    修改第一套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();
  }
}
  1. 修正代码笔误
    你Controller中/view接口的注解参数拼写错误,param需要改为params:
// 修正前
@PostMapping(path="/view", param = "!ACTION")
// 修正后
@PostMapping(path="/view", params = "!ACTION")

内容的提问来源于stack exchange,提问作者Mohit Shrivastava

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.18 08:24:03