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

使用Spring Security 6.2.4时找不到hasScope及authorize方法求助

解决Spring Security 6.2.4中hasScope校验及authorizeRequests过时问题

问题根源

  1. authorizeRequests已废弃:Spring Security 6.x起官方推荐使用authorizeHttpRequests替代过时的authorizeRequests,两者的DSL语法结构存在差异。
  2. hasScope类路径变更:你参考的文档示例适配旧版本,6.x中hasScope已从OAuth2AuthorizationManagers迁移至JwtAuthorizationManagers类下。

修正后的完整配置代码

import org.springframework.security.oauth2.server.resource.authentication.JwtAuthorizationManagers.hasScope

@Configuration
@EnableWebSecurity
class MyCustomSecurityConfiguration {
    @Bean
    fun filterChain(http: HttpSecurity): SecurityFilterChain {
        http {
            authorizeHttpRequests {
                authorize("/messages/**", hasScope("message:read"))
                authorize(anyRequest, authenticated)
            }
            oauth2ResourceServer {
                jwt {
                    jwtAuthenticationConverter = myConverter()
                }
            }
        }
        return http.build()
    }

    // 实现自定义JWT转换器逻辑
    private fun myConverter(): JwtAuthenticationConverter {
        val converter = JwtAuthenticationConverter()
        // 此处添加你的自定义转换规则,比如映射权限等
        return converter
    }
}

关键说明

  • 正确导入hasScope:必须导入org.springframework.security.oauth2.server.resource.authentication.JwtAuthorizationManagers.hasScope,这是Spring Security 6.x中JWT资源服务器场景的正确路径。
  • authorizeHttpRequests语法验证:6.x的Kotlin DSL中authorizeHttpRequests下的authorize方法是可用的,若仍报错,检查是否存在拼写错误或依赖缺失。
  • 依赖完整性检查:确保项目依赖中包含完整的Spring Security OAuth2资源服务器组件,以Gradle为例:
    implementation("org.springframework.boot:spring-boot-starter-security")
    implementation("org.springframework.boot:spring-boot-starter-oauth2-resource-server")
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 00:42:34