You need to enable JavaScript to run this app. Spring Boot项目Spring Security JDBC认证登录失败问题求助
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot项目Spring Security JDBC认证登录失败问题求助

问题排查及解决方案

核心问题1:权限表字段名与查询语句不匹配

你使用@ElementCollection存储Authorities可嵌入对象时,JPA默认会给嵌入类的字段添加前缀,Authorities类的authority字段在authorities表中对应的默认列名为authorities_authority,但你在安全配置中写的权限查询语句是:

select username, authority from authorities where username=?

查询的列名authority不存在,导致无法读取用户权限,认证流程中断。

核心问题2:Authorities类缺少权限字段的Getter方法

Spring Security加载用户权限时需要通过反射读取authority字段的值,你当前的Authorities类没有提供getAuthority()方法,无法正常获取权限值,也会导致认证失败。

可选检查项

  • 确认数据库中users表的enabled字段值为1(即true),如果用户处于禁用状态也会登录失败
  • 确认注册用户时加密密码使用的BCryptPasswordEncoder实例与安全配置中使用的是同一个实现,避免版本/强度不匹配导致密码校验失败

具体修复步骤

  1. 修改Authorities类,添加Getter和指定列名
@Embeddable
public class Authorities{

    @Column(name = "authority") // 强制指定列名,避免JPA自动加前缀
    private String authority;

    public Authorities() {}

    public Authorities(String authority) {
        this.authority = authority;
    }

    // 添加getter方法
    public String getAuthority() {
        return authority;
    }

    public void setAuthority(String authority) {
        this.authority = authority;
    }
}
  1. (可选)如果不想修改实体类,可直接修改安全配置中的权限查询语句,适配默认生成的列名:
.authoritiesByUsernameQuery("select username, authorities_authority as authority from authorities where username=?");
  1. 重启项目重新测试登录即可。

内容的提问来源于stack exchange,提问作者Marco Antonio Francis Pereira

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.10 11:24:03