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

Spring Security角色权限失效:已认证请求仍返回403 Forbidden

Spring Security 403 Forbidden 排查方案

核心问题定位

你遇到的问题是权限字符串不匹配:Spring Security的hasRole()方法会自动给角色名添加ROLE_前缀,但你的用户权限集合中存储的是原始角色名(如SELLER),导致权限校验失败。

具体排查与解决步骤

1. 修正权限前缀匹配

有两种方案可选:

  • 方案一:给权限添加ROLE_前缀
    修改User类的getAuthorities()方法,给角色名加上前缀:

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return this.roles.stream().map(r -> new RoleGrantedAuthority("ROLE_" + r.name())).collect(Collectors.toList());
    }
    

    这样hasRole("SELLER")会匹配ROLE_SELLER权限,校验通过。

  • 方案二:改用hasAuthority()替代hasRole()
    hasAuthority()不会自动添加前缀,直接匹配原始权限字符串,修改SecurityConfig:

    .antMatchers("/api/auth/seller/**").hasAuthority("SELLER")
    .antMatchers("/api/auth/consumer/**").hasAuthority("CONSUMER")
    

2. 验证Authentication对象权限

在你的JwtAuthenticationFilter中添加日志,确认SecurityContext中的权限是否正确:

// 在设置Authentication到SecurityContext之前添加日志
UsernamePasswordAuthenticationToken authToken = new UsernamePasswordAuthenticationToken(user, null, user.getAuthorities());
System.out.println("当前用户权限列表:" + authToken.getAuthorities());
SecurityContextHolder.getContext().setAuthentication(authToken);

启动项目调用接口,查看控制台输出的权限字符串,确保和SecurityConfig中的校验规则匹配。

3. 检查Role枚举拼写

确认你的Role枚举中的值(SELLER、CONSUMER)大小写、拼写完全正确,Spring Security权限匹配是大小写敏感的。

4. 开启调试日志排查细节

在application.properties中添加日志配置:

logging.level.org.springframework.security=DEBUG

调用接口时,控制台会输出权限校验的完整流程,例如:

Checking match of request : '/api/auth/seller/list'; against '/api/public/**'
Checking match of request : '/api/auth/seller/list'; against '/api/auth/seller/**'
Access is denied (user is authenticated); authorities [SELLER]

从日志中可以直观看到用户拥有的权限和接口要求的权限是否匹配。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.20 23:12:50