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

从Spring迁移至Spring Boot后Spring Security认证失效问题咨询

Spring Security认证失效问题排查方案

1. 修正CSRF配置

当前配置中http.csrf().and()仅声明CSRF配置项未关闭防护,Spring Boot默认开启CSRF校验,登录表单未携带CSRF Token时会直接被拦截返回403错误,可选择两种修复方案:

  • 测试阶段临时关闭CSRF:修改配置为http.csrf().disable().and().headers()...
  • 生产环境保留CSRF:在登录表单添加CSRF Token隐藏域,示例如下:
<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />

2. 补充登录相关路径放行规则

现有配置未对登录页面、登录提交接口做权限放行,未登录状态下访问相关路径会直接被拦截,调整后的完整配置参考:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable()
            .authorizeRequests()
            // 放行登录相关资源与接口
            .antMatchers("/login.html", "/j_spring_security_check").permitAll()
            .anyRequest().authenticated()
            .and()
            .headers().and().anonymous().disable()
            .formLogin().loginPage("/login.html").failureHandler(this.authenticationFailureHandler)
            .defaultSuccessUrl("/main").loginProcessingUrl("/j_spring_security_check")
            .usernameParameter("j_username").passwordParameter("j_password")
            .and()
            .logout().logoutUrl("/j_spring_security_logout").logoutSuccessUrl("/login.html");
}

3. 校验登录表单参数配置

确认登录页面的表单满足以下要求:

  • 提交方式为POST
  • 提交地址对应配置的/j_spring_security_check
  • 账号输入框name属性为j_username,密码输入框name属性为j_password

4. 开启Debug日志定位深层问题

如果以上配置调整后仍未解决,可在application.yml中开启Spring Security debug日志:

logging:
  level:
    org.springframework.security: DEBUG

提交登录请求后查看日志的拦截链执行记录,可定位到具体拦截节点与异常原因,比如账号密码错误、用户状态异常等都会触发认证失败。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.12 06:12:04