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

Spring configure方法未调用:URL编码斜杠配置不生效求助

解决Spring Security允许URL编码斜杠配置不生效的问题

我来帮你一步步排查和解决这个问题——核心症结应该是configure(WebSecurity)方法没被执行,导致自定义的HttpFirewall配置没被应用上。

一、先确认@EnableWebSecurity注解是否正确配置

你提到已经添加了@EnableWebSecurity,但看你贴的代码里只标注了@Configuration,这个注解是激活Spring Security配置的关键,必须确保它和@Configuration一起加在你的配置类上,否则Spring Security不会识别并执行类中的配置方法:

@Configuration
@EnableWebSecurity // 这个注解不能漏!
public class SecurityConfiguration extends WebSecurityConfigurerAdapter {
    // 你的原有代码...
}

二、排查配置类是否被Spring正确扫描

如果注解都加对了但方法还是没执行,大概率是这个配置类不在Spring的组件扫描范围内:

  • 检查SecurityConfiguration所在的包,是否被启动类的@SpringBootApplication(或单独的@ComponentScan)扫描路径覆盖
  • 也可以尝试给配置类额外加上@Component注解(虽然@Configuration本身包含@Component,但极端情况下能解决扫描问题)

三、改用Spring Security推荐的新配置方式(更稳定)

WebSecurityConfigurerAdapter在Spring Boot 2.7及以上版本已经被弃用,官方推荐用WebSecurityCustomizer替代原有的configure(WebSecurity)方法,这种方式更符合当前最佳实践,也能避免旧API的潜在问题:

@Configuration
@EnableWebSecurity
public class SecurityConfiguration {

    @Bean
    public HttpFirewall allowUrlEncodedSlashHttpFirewall() {
        DefaultHttpFirewall firewall = new DefaultHttpFirewall();
        firewall.setAllowUrlEncodedSlash(true);
        return firewall;
    }

    @Bean
    public WebSecurityCustomizer webSecurityCustomizer() {
        // 绑定自定义的HttpFirewall
        return web -> web.httpFirewall(allowUrlEncodedSlashHttpFirewall());
    }
}

四、额外排查:是否有其他Security配置类冲突

如果项目里存在多个标注@EnableWebSecurity的配置类,可能会覆盖当前配置:

  • 检查项目中是否有其他Security配置类
  • 若需要指定优先级,可以给当前配置类加上@Order(1)(数值越小优先级越高)

五、验证配置是否生效

配置完成后,可以通过两种方式验证:

  1. 调用包含编码斜杠(比如%2F)的测试URL,看是否能正常访问
  2. 在allowUrlEncodedSlashHttpFirewall()方法里加日志或断点,确认这个Bean被创建并成功应用

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 05:05:21