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

Spring Security所有表单POST请求均返回403 Forbidden问题求助

解决Spring Security引入后POST请求返回403的问题

看起来你遇到的问题核心在于Spring Security配置类的实现方式不对,导致你的CSRF禁用规则根本没生效,我来帮你一步步解决:

核心错误点

你的WebSecurityConfig实现了WebMvcConfigurer接口,但这个接口是用来配置Spring MVC(比如视图解析、静态资源映射)的,和Spring Security的配置逻辑完全不相关。你写的configure(HttpSecurity http)方法只是一个普通方法,Spring Security根本不会识别并执行它,所以csrf().disable()的配置等于白加,POST请求依然被默认的CSRF防护拦截,返回403。

Spring Security的自定义配置应该通过**继承WebSecurityConfigurerAdapter**来实现,这个适配器是Spring Security提供的专门用来扩展安全规则的基类。

修正后的配置代码

@EnableWebSecurity
// 替换为继承WebSecurityConfigurerAdapter,而非实现WebMvcConfigurer
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
    // 加上@Override注解,确保重写的是适配器中的正确方法
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
            .authorizeRequests()
            .anyRequest().authenticated()
            .and()
            .formLogin() // 保留默认表单登录
            .and()
            .httpBasic() // 保留HTTP Basic认证
            .and()
            .csrf().disable(); // 现在这个配置会被Spring Security正确加载
    }

    @Bean
    public UserDetailsService userDetailsService() throws Exception {
        InMemoryUserDetailsManager manager = new InMemoryUserDetailsManager();
        manager.createUser(User.withDefaultPasswordEncoder()
            .username("user")
            .password("password")
            .roles("USER")
            .build());
        return manager;
    }
}

额外建议(生产环境推荐)

完全禁用CSRF防护只适合测试环境,生产环境建议保留CSRF防护,只需要在你的表单中添加CSRF令牌即可:

  • 如果用Thymeleaf模板,直接添加以下代码:
    <input type="hidden" th:name="${_csrf.parameterName}" th:value="${_csrf.token}" />
    
  • 如果用JSP,添加:
    <input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />
    

这样Spring Security就会验证表单中的CSRF令牌,POST请求就能正常通过了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.13 09:24:59