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

Spring Boot 2.7+替换ResourceServerConfigurerAdapter配置方案

Spring Boot 2.7+ 旧版OAuth2资源服务器配置迁移方案

你找不到@EnableResourceServer和ResourceServerConfigurerAdapter的组件式配置适配指引是正常的——这两个类属于早已停止维护的旧版spring-security-oauth2模块,Spring Security 5.2版本之后已经将OAuth2资源服务器能力内置到核心框架中,官方直接用全新的内置DSL替代了旧的Adapter实现,不需要再对旧类做适配。

迁移前置依赖调整

首先移除项目中旧的OAuth2依赖(包括spring-security-oauth2、spring-security-oauth2-autoconfigure),替换为Spring Boot官方封装的资源服务器Starter:

<!-- Maven依赖示例 -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-oauth2-resource-server</artifactId>
</dependency>

配置逻辑对应迁移

你原来的配置逻辑可以1:1映射到新的组件式配置,完全不需要继承任何Adapter类,只需要注册SecurityFilterChain类型的Bean即可:

@Configuration
public class BearerAuthWebSecurityConfiguration {

    @Bean
    public SecurityFilterChain apiSecurityFilterChain(HttpSecurity http) throws Exception {
        http
                // 对应原配置的antMatcher("/api/**"),指定当前安全链仅拦截/api路径下的请求
                .securityMatcher("/api/**")
                // 替换原@EnableResourceServer的资源服务器能力,若使用透明令牌请替换为opaqueToken()配置
                .oauth2ResourceServer(OAuth2ResourceServerConfigurer::jwt)
                // 对应原配置的无状态会话策略
                .sessionManagement(session -> session
                        .sessionCreationPolicy(SessionCreationPolicy.STATELESS)
                )
                // 对应原配置的所有请求需认证规则,Spring 6/Spring Boot 3中已废弃authorizeRequests,推荐使用authorizeHttpRequests
                .authorizeHttpRequests(auth -> auth
                        .anyRequest().authenticated()
                );

        return http.build();
    }
}

原配置特殊项说明

你原来在ResourceServerSecurityConfigurer中配置的两个特殊项不需要手动复刻,框架已经自动处理:

  • resources.resourceId(null):新版内置资源服务器默认不强制校验资源ID(aud字段),如果后续需要加资源ID校验,直接在JWT解码器/不透明令牌校验器中添加对应校验规则即可,不需要全局配置。
  • resources.authenticationManager(new OAuth2AuthenticationManager()):oauth2ResourceServer()DSL会自动装配适配资源服务器场景的AuthenticationManager实例,不需要手动实例化,性能和兼容性比旧版手动new的实现更好。如果需要自定义认证逻辑,直接在DSL中通过authenticationManagerResolver方法注入自定义实现即可。

注意事项

  • 如果项目中存在多组路径的安全规则,分别定义多个SecurityFilterChain Bean即可,可通过@Order注解指定链的匹配优先级。
  • 配置JWT校验的密钥/证书地址、不透明令牌的校验端点等参数,直接在application.yml中通过spring.security.oauth2.resourceserver前缀的配置项设置即可,不需要写硬编码配置。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 13:51:28