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

Spring Boot Security登录成功后始终返回403 Forbidden求助

解决Spring Boot Security登录后始终返回403 Forbidden的问题

核心问题分析

你的问题根源在于Spring Security角色权限的前缀匹配规则:

  • 使用hasRole("USER")时,框架会自动给角色名添加ROLE_前缀,实际校验的是ROLE_USER权限
  • 但你数据库中存储的角色是USER、ADMIN,没有ROLE_前缀,导致权限校验不通过,返回403

解决方案(二选一即可)

方案1:给角色添加ROLE_前缀(推荐)

修改TbUser类的getAuthorities()方法,在创建SimpleGrantedAuthority时手动添加前缀:

@Override
public Collection<? extends GrantedAuthority> getAuthorities() {
    String[] roles = role.split(",");
    List<SimpleGrantedAuthority> authorities = new ArrayList<>();
    for (String role : roles) {
        // 为角色添加ROLE_前缀,适配hasRole的校验规则
        authorities.add(new SimpleGrantedAuthority("ROLE_" + role));
    }
    return authorities;
}

方案2:改用hasAuthority方法校验权限

修改SecurityConfig的configure(HttpSecurity http)方法,用hasAuthority替代hasRole,该方法不会自动添加前缀,直接匹配数据库中的角色名:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.csrf().disable();
    http.authorizeRequests()
            .antMatchers("/api/user/**").hasAuthority("USER")
            .antMatchers("/api/admin/**").hasAuthority("ADMIN")
            .anyRequest().authenticated()
            .and()
            .formLogin()
            .and()
            .httpBasic();
}

额外检查点

确保你的CustomPwdEncoder正确实现了PasswordEncoder接口,因为数据库中存储的是明文密码,需要让编码器能正确验证:

public class CustomPwdEncoder implements PasswordEncoder {
    @Override
    public String encode(CharSequence rawPassword) {
        // 注意:生产环境必须使用BCrypt等加密算法,此处仅适配明文测试场景
        return rawPassword.toString();
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {
        return rawPassword.toString().equals(encodedPassword);
    }
}

内容的提问来源于stack exchange,提问作者great-jin

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.24 23:22:45