org.springframework.security.web.firewall.RequestRejectedException: The request was rejected because the URL contained a potentially malicious String "//"
时间: 2025-03-13 07:13:29 浏览: 58
### Spring Security 中因 URL 包含双斜杠 (`//`) 导致 `RequestRejectedException` 的解决方案
当应用程序使用 Spring Security 并启用了默认的安全配置时,如果请求的 URL 中包含恶意字符串(如双斜杠 `//`),Spring Security 将抛出 `RequestRejectedException` 异常。这是由于 Spring Security 默认启用了一个名为 `StrictHttpFirewall` 的组件来防止潜在的 HTTP 请求攻击[^2]。
#### 解决方案一:自定义 HttpFirewall 配置
可以通过替换默认的 `StrictHttpFirewall` 实现来自定义防火墙行为。具体方法如下:
1. 创建一个新的类继承 `StrictHttpFirewall` 或实现 `HttpFirewall` 接口。
2. 调整允许通过的 URL 特征,例如允许双斜杠的存在。
以下是代码示例:
```java
import org.springframework.security.web.firewall.StrictHttpFirewall;
import org.springframework.security.web.firewall.HttpFirewall;
public class CustomHttpFirewall extends StrictHttpFirewall {
@Override
public void configure(HttpFirewall firewall) {
super.configure(firewall);
setAllowUrlEncodedSlash(true); // 允许编码后的斜杠
setAllowSemicolonInPath(true); // 如果需要也可以允许可疑字符
}
}
```
接着,在 Spring 安全配置中注入该自定义防火墙实例:
```java
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.firewall.HttpFirewall;
@Configuration
public class WebSecurityConfig {
@Bean
public HttpFirewall allowUrlEncodedForwardSlashes() {
return new CustomHttpFirewall();
}
@Bean
protected SecurityFilterChain configure(HttpSecurity http) throws Exception {
http
.csrf().disable()
.authorizeRequests()
.antMatchers("/public/**").permitAll()
.anyRequest().authenticated()
.and()
.sessionManagement().sessionCreationPolicy(SessionCreationPolicy.STATELESS);
http.setFirewall(allowUrlEncodedForwardSlashes());
return http.build();
}
}
```
此方式可以有效控制哪些特定情况下的 URL 不被拒绝,同时保留其他安全特性[^3]。
#### 解决方案二:禁用 DefaultHttpFirewall
另一种更简单的方式是完全禁用默认的 `StrictHttpFirewall`,但这可能会降低安全性。可以在应用属性文件中设置以下参数:
```properties
spring.security.filter.chain.proxy-firewall=false
```
或者在 Java 配置中显式关闭防火墙功能:
```java
@Bean
public HttpFirewall defaultHttpFirewall() {
return new DefaultHttpFirewall(); // 使用较宽松的防火墙策略
}
```
需要注意的是,默认情况下 `DefaultHttpFirewall` 对某些危险字符不会进行严格过滤,因此仅适用于开发环境或低风险场景下测试用途[^4]。
---
### 总结
上述两种方法均可解决由双斜杠引起的 `RequestRejectedException` 问题。推荐优先采用 **解决方案一** 来定制化需求并保持较高的安全性标准;而 **解决方案二** 则适合快速验证逻辑但在生产环境中需谨慎对待。
阅读全文