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

Spring Boot 3.2 OAuth2令牌服务开发:废弃类替代方案咨询

Spring Boot 3.2 中 OAuth2 非JWT令牌服务开发方案

核心结论:Spring Boot 2 的旧方案已被替代

Spring Boot 2 中依赖的AuthorizationServerConfigurerAdapter、TokenStore等类属于旧版Spring Security OAuth2授权服务器模块,该模块已从Spring Security核心中移除,在Spring Boot 3.x中完全废弃且不再维护,无法直接沿用旧方案。当前官方推荐使用Spring Authorization Server(独立项目)来实现OAuth2授权服务。

非JWT令牌(Opaque Token)的实现方案

如果你需要的是不透明的OAuth2令牌(而非JWT),核心在于让授权服务器存储令牌元数据,客户端每次请求资源服务器时,资源服务器需向授权服务器验证令牌有效性。以下是具体实现步骤:

1. 引入依赖

在pom.xml(Maven)或build.gradle(Gradle)中添加Spring Authorization Server和Spring Security依赖:

<!-- Maven -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.security</groupId>
    <artifactId>spring-security-oauth2-authorization-server</artifactId>
    <version>1.2.3</version> <!-- 适配Spring Boot 3.2的最新稳定版 -->
</dependency>

2. 配置授权服务器组件

2.1 注册客户端信息

通过RegisteredClientRepository定义OAuth2客户端,替代旧版的客户端配置:

@Bean
public RegisteredClientRepository registeredClientRepository() {
    RegisteredClient client = RegisteredClient.withId(UUID.randomUUID().toString())
            .clientId("your-client-id")
            .clientSecret("{bcrypt}your-encoded-secret") // 用PasswordEncoder加密
            .clientAuthenticationMethod(ClientAuthenticationMethod.CLIENT_SECRET_BASIC)
            .authorizationGrantType(AuthorizationGrantType.AUTHORIZATION_CODE)
            .authorizationGrantType(AuthorizationGrantType.PASSWORD) // 如果需要密码模式
            .authorizationGrantType(AuthorizationGrantType.CLIENT_CREDENTIALS)
            .redirectUri("http://localhost:8080/login/oauth2/code/your-client")
            .scope("read")
            .scope("write")
            .clientSettings(ClientSettings.builder().requireAuthorizationConsent(true).build())
            .build();

    return new InMemoryRegisteredClientRepository(client);
}

2.2 配置令牌存储(替代TokenStore)

对于非JWT令牌,需使用服务器端存储来保存授权信息。内存存储适合开发测试,生产环境推荐JDBC存储:

// 内存存储(开发用)
@Bean
public OAuth2AuthorizationService authorizationService() {
    return new InMemoryOAuth2AuthorizationService();
}

// JDBC存储(生产用,需引入spring-boot-starter-jdbc并配置数据库)
// @Bean
// public OAuth2AuthorizationService authorizationService(JdbcTemplate jdbcTemplate, RegisteredClientRepository registeredClientRepository) {
//     return new JdbcOAuth2AuthorizationService(jdbcTemplate, registeredClientRepository);
// }

// 对应令牌生成器,生成不透明令牌
@Bean
public OAuth2TokenGenerator<?> tokenGenerator() {
    OAuth2AccessTokenGenerator accessTokenGenerator = new OAuth2AccessTokenGenerator();
    accessTokenGenerator.setAccessTokenCustomizer(tokenContext -> {
        // 可自定义令牌属性
    });
    return new DelegatingOAuth2TokenGenerator(accessTokenGenerator, new OAuth2RefreshTokenGenerator());
}

2.3 配置授权服务器SecurityFilterChain

替代旧版的授权服务器配置,使用FilterChain模式:

@Bean
@Order(1)
public SecurityFilterChain authorizationServerSecurityFilterChain(HttpSecurity http) throws Exception {
    OAuth2AuthorizationServerConfiguration.applyDefaultSecurity(http);
    http.getConfigurer(OAuth2AuthorizationServerConfigurer.class)
            .oidc(Customizer.withDefaults()); // 可选,启用OIDC支持

    http.exceptionHandling(exceptions -> exceptions
            .authenticationEntryPoint(new LoginUrlAuthenticationEntryPoint("/login")));

    return http.build();
}

3. 配置用户认证与普通Web安全

@Bean
@Order(2)
public SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
    http.authorizeHttpRequests(authorize -> authorize
            .anyRequest().authenticated())
            .formLogin(Customizer.withDefaults());

    return http.build();
}

@Bean
public UserDetailsService userDetailsService() {
    UserDetails user = User.withUsername("user")
            .password("{bcrypt}encoded-password")
            .roles("USER")
            .build();

    return new InMemoryUserDetailsManager(user);
}

@Bean
public PasswordEncoder passwordEncoder() {
    return new BCryptPasswordEncoder();
}

关键文档参考

  • Spring Authorization Server官方文档:聚焦OAuth2授权服务器的配置细节,包含非JWT令牌的存储与验证说明
  • Spring Security官方文档的OAuth2章节:讲解新版Security与Authorization Server的集成逻辑

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 03:05:13