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

Spring Boot资源服务器@PreAuthorize(SCOPE权限校验)失效问题

问题排查与解决

你的核心问题是方法级权限控制未被启用,Spring Security默认不会自动激活@PreAuthorize这类注解的校验逻辑,所以即使你在方法上标注了权限规则,也不会生效。

解决步骤

  1. 创建或修改你的Spring Security配置类,添加@EnableMethodSecurity注解(适用于Spring Boot 2.7+版本,也是当前spring-boot-starter-oauth2-resource-server对应的主流版本):
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

@Configuration
@EnableWebSecurity
@EnableMethodSecurity
public class ResourceServerSecurityConfig {
    // 可在此添加资源服务器的其他配置,比如JWT验证规则等
}

如果你的Spring Boot版本低于2.7,需要替换为@EnableGlobalMethodSecurity(prePostEnabled = true):

import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;

@Configuration
@EnableWebSecurity
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class ResourceServerSecurityConfig {
    // 配置内容
}
  1. 重启应用后,再用带有items.read的Token访问/with-role-security接口,会收到403 Forbidden的响应,符合预期的权限控制逻辑。

补充说明

从你提供的日志可以看到,JWT的权限已经被正确解析为Granted Authorities(SCOPE_items.read和SCOPE_items.write),只是权限校验逻辑没有被触发。启用方法级安全后,Spring Security会拦截带有@PreAuthorize注解的方法,执行配置的权限校验规则。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 22:22:30