Spring Security请求被拒:URL含潜在恶意字符串//的处理咨询
RequestRejectedException异常处理方案
异常原因
Spring Security默认启用的StrictHttpFirewall会拦截包含//的请求URL,因为双斜杠被判定为潜在恶意字符串,这是框架内置的安全防护策略,用于防范路径遍历等攻击行为。
可行解决方案
1. 自定义防火墙规则允许双斜杠
仅在业务确实需要支持含//的URL时使用,需创建Spring配置类修改防火墙参数:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.web.firewall.HttpFirewall; import org.springframework.security.web.firewall.StrictHttpFirewall; @Configuration public class SecurityFirewallConfig { @Bean public HttpFirewall customHttpFirewall() { StrictHttpFirewall firewall = new StrictHttpFirewall(); // 允许明文双斜杠 firewall.setAllowDoubleSlash(true); // 若URL包含编码后的%2F%2F,需开启此配置 firewall.setAllowUrlEncodedDoubleSlash(true); return firewall; } }
⚠️ 注意:此配置会降低安全防护等级,需确保请求来源可信,避免引入安全风险。
2. 修复请求URL(推荐)
从根源解决问题,确保前端或服务调用方发送的URL中不存在//,将路径中的双斜杠替换为单斜杠。例如将http://your-domain/api//resource修正为http://your-domain/api/resource。
3. 全局捕获异常返回友好响应
如果不需要修改防火墙规则,可通过全局异常处理器捕获该异常,返回标准化错误信息:
import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.security.web.firewall.RequestRejectedException; import org.springframework.web.bind.annotation.ControllerAdvice; import org.springframework.web.bind.annotation.ExceptionHandler; @ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(RequestRejectedException.class) public ResponseEntity<String> handleRequestRejection(RequestRejectedException ex) { return ResponseEntity.status(HttpStatus.BAD_REQUEST) .body("请求格式非法:" + ex.getMessage()); } }
内容的提问来源于stack exchange,提问作者alexanoid
相关产品推荐
相关产品推荐

