You need to enable JavaScript to run this app. Spring Security4升级至5后POST请求/j_spring_security_check不支持问题
优惠活动
大模型
产品
解决方案
定价
更多

Spring Security4升级至5后POST请求/j_spring_security_check不支持问题

问题根因定位

你遇到的Request method 'POST' not supported报错,本质是/j_spring_security_check请求没有被Spring Security的UsernamePasswordAuthenticationFilter处理,直接透传给了Spring MVC控制器,而你没有写对应路径的POST接口,所以MVC抛出了该错误。

核心触发原因是Spring Security 4到5.x的两个关键变更:

  1. 配置生效规则变更:Spring Security 5.x要求必须显式配置授权规则(即authorizeRequests()相关配置),如果你的配置里仅写了formLogin、logout等逻辑,缺少anyRequest().authenticated()这类授权声明,Spring Security的Filter链不会主动拦截除内置默认路径外的自定义登录处理路径,导致你的/j_spring_security_check配置失效。
  2. Filter初始化逻辑变更:Spring Security 5.x中,自定义loginProcessingUrl的生效前提是该路径被纳入Spring Security的拦截范围,没有授权规则的情况下自定义路径不会被Filter处理。

排查&解决步骤
  • 第一步:补全HttpSecurity的授权规则配置,在你现有配置的末尾(//Custom filters注释之前)添加如下代码:
http.authorizeRequests()
        // 所有请求都需要认证,保证登录处理路径被Filter拦截
        .anyRequest().authenticated();
  • 第二步:确认你的Spring Security配置类上同时标注了@Configuration和@EnableWebSecurity注解,Spring Security 5.x中缺失@EnableWebSecurity会导致自定义配置不生效。
  • 第三步:如果是传统非Spring Boot项目,确认web.xml中已经正确注册了Spring Security的Filter:
<filter>
    <filter-name>springSecurityFilterChain</filter-name>
    <filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
    <filter-name>springSecurityFilterChain</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>
  • 第四步:如果上述配置都正确,可在UsernamePasswordAuthenticationFilter的attemptAuthentication方法处打端点,确认请求是否进入该方法;如果没有进入,检查是否有自定义Filter提前拦截了登录请求。

额外验证点

如果升级后还出现密码校验失败的问题,是因为Spring Security 5.x默认要求密码存储格式必须带上前缀(比如{bcrypt}),如果你的旧密码是明文或者无前缀的加密存储,需要修改密码编码器配置,或者在密码前加上对应加密方式的前缀即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 22:24:06