You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot+Spring Security:如何触发并查看RequestRejectedException日志?

RequestRejectedException无ERROR级日志的原因及解决办法

核心原因

1. 默认处理器仅输出DEBUG级日志

Spring Security处理RequestRejectedException的默认实现是DefaultRequestRejectedHandler,这个类内部仅在DEBUG日志级别下打印异常详情,核心逻辑如下:

public void handle(HttpServletRequest request, HttpServletResponse response, RequestRejectedException requestRejectedException) throws IOException, ServletException {
    if (this.logger.isDebugEnabled()) {
        this.logger.debug("Rejected request since it contained potentially malicious content", requestRejectedException);
    }
    response.sendError(400);
}

如果你的日志配置(比如application.properties、logback-spring.xml)没有开启org.springframework.security.web.firewall包的DEBUG级别,控制台和日志文件自然看不到这条日志。

2. 异常未进入Spring MVC的异常处理流程

RequestRejectedException是在Spring Security的过滤器链(Filter Chain)中被抛出的,这个阶段早于Spring MVC的DispatcherServlet执行,所以不会被@ControllerAdvice或@ExceptionHandler这类全局异常处理器捕获,也就无法触发常规的ERROR级日志输出。

解决办法

方法1:调整日志级别,开启DEBUG输出

在日志配置中,开启Spring Security防火墙相关包的DEBUG级别:

  • 若使用application.properties:
logging.level.org.springframework.security.web.firewall=DEBUG
  • 若使用logback.xml:
<logger name="org.springframework.security.web.firewall" level="DEBUG"/>

这样就能看到你期望的异常详情,但注意DEBUG日志量会有所增加。

方法2:自定义RequestRejectedHandler,输出ERROR级日志

创建自定义处理器替换默认实现,在处理异常时打印ERROR级别日志:

@Component
public class CustomRequestRejectedHandler implements RequestRejectedHandler {

    private static final Logger logger = LoggerFactory.getLogger(CustomRequestRejectedHandler.class);

    @Override
    public void handle(HttpServletRequest request, HttpServletResponse response, RequestRejectedException ex) throws IOException {
        logger.error("请求被拒绝:URL包含潜在恶意字符串", ex);
        response.sendError(HttpServletResponse.SC_BAD_REQUEST, "Invalid request");
    }
}

然后在Spring Security配置中注册该处理器:

@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Autowired
    private CustomRequestRejectedHandler customRequestRejectedHandler;

    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        http
            // 其他配置...
            .requestRejectedHandler(customRequestRejectedHandler);
        return http.build();
    }
}

这样既能输出ERROR级的异常日志,也能自定义错误响应逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 16:04:59