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

如何仅对单个URL启用Spring Security认证?

Spring Security拦截含"//"URL的解决办法

问题根源

Spring Security默认用StrictHttpFirewall做请求安全校验,它会直接拦截包含**连续斜杠(//)**的URL——哪怕你已经配置了其他URL无需认证,防火墙的拦截优先级更高,所以会抛出RequestRejectedException。

解决步骤

自定义HttpFirewall规则,允许连续斜杠的URL,再把这个规则配置到Spring Security里。

完整代码示例

1. 定义允许连续斜杠的HttpFirewall

@Bean
public HttpFirewall customHttpFirewall() {
    StrictHttpFirewall firewall = new StrictHttpFirewall();
    // 放行URL中的连续斜杠
    firewall.setAllowUrlEncodedDoubleSlash(true);
    // 要是还有其他需要放行的特殊字符,比如反斜杠,也可以在这里加
    // firewall.setAllowUrlEncodedBackSlash(true);
    return firewall;
}

2. 更新SecurityFilterChain配置

把自定义的HttpFirewall注入进去,替换默认的防火墙规则:

@Bean
public SecurityFilterChain securityFilterChain(HttpSecurity http, HttpFirewall customHttpFirewall) throws Exception {
    http
        .authorizeHttpRequests(auth -> auth
            .antMatchers("/actuator/health").authenticated()
            .anyRequest().permitAll()
        )
        .httpBasic()
        .and()
        // 应用自定义防火墙
        .csrf().disable() // 根据业务需求决定是否关闭CSRF,非必须
        .setSharedObject(HttpFirewall.class, customHttpFirewall);

    return http.build();
}

注意事项

放宽防火墙规则会降低部分安全防护,确认你的业务场景中这类带连续斜杠的URL是合法且安全的,避免被恶意利用。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 03:52:02