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实例与安全配置中使用的是同一个实现,避免版本/强度不匹配导致密码校验失败
具体修复步骤
- 修改
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; } }
- (可选)如果不想修改实体类,可直接修改安全配置中的权限查询语句,适配默认生成的列名:
.authoritiesByUsernameQuery("select username, authorities_authority as authority from authorities where username=?");
- 重启项目重新测试登录即可。
内容的提问来源于stack exchange,提问作者Marco Antonio Francis Pereira
相关产品推荐
相关产品推荐

