Spring Boot 3.0.1实现Token在线验证的安全配置方案
Spring Boot 3.0.1 配置远程JWT Token校验(禁用离线公钥模式)
你的场景核心是让API通过远程调用OIDC Provider的Token introspection端点来校验JWT有效性,而非本地用公钥验签。Spring Security OAuth2 Resource Server已经原生支持这个能力,具体配置步骤如下:
1. 添加必要依赖
在pom.xml(Maven)或build.gradle(Gradle)中引入Spring Security OAuth2资源服务器的starter:
Maven
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-oauth2-resource-server</artifactId> </dependency>
Gradle
implementation 'org.springframework.boot:spring-boot-starter-oauth2-resource-server'
2. 配置OIDC Provider与远程校验参数
在application.yml(或application.properties)中指定OIDC的 issuer地址、用于调用introspection端点的客户端凭证,同时禁用本地JWT校验,强制使用远程 introspection:
spring: security: oauth2: resourceserver: jwt: # 禁用本地JWT验签,强制走远程校验 issuer-uri: ${OIDC_ISSUER_URL} # 替换为你的OIDC Provider地址,比如https://your-oidc-provider.com jwk-set-uri: null # 设为null,避免加载公钥进行本地校验 introspection: client-id: ${OIDC_INTROSPECTION_CLIENT_ID} # OIDC Provider分配的用于introspection的客户端ID client-secret: ${OIDC_INTROSPECTION_CLIENT_SECRET} # 对应的客户端密钥 uri: ${OIDC_INTROSPECTION_URL} # 可选:如果OIDC Provider的introspection端点不是默认路径,可手动指定
注:大部分合规的OIDC Provider会通过
/.well-known/openid-configuration暴露introspection端点地址,符合规范的话uri可省略,Spring会自动从issuer元数据中获取。
3. 配置Spring Security过滤链
创建一个Security配置类,设置资源服务器规则,确保所有请求都经过Token校验,同时指定使用introspection模式:
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; import org.springframework.security.web.SecurityFilterChain; import org.springframework.security.oauth2.server.resource.web.BearerTokenAuthenticationConverter; @Configuration @EnableWebSecurity public class ResourceServerConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth .anyRequest().authenticated() // 所有请求都需要认证 ) .oauth2ResourceServer(oauth2 -> oauth2 .introspection(introspection -> introspection // 若BFF转发的Token在默认Authorization头中,无需额外配置;否则可自定义Token提取逻辑 .tokenConverter(new BearerTokenAuthenticationConverter()) ) ); return http.build(); } }
关键说明
- 禁用本地校验逻辑:通过
jwk-set-uri: null阻止Spring加载OIDC Provider的公钥,强制触发远程introspection校验流程。 - 客户端权限配置:确保在OIDC Provider中创建的客户端拥有调用introspection端点的权限,通常需要开启"Token Introspection"相关授权。
- Token传递要求:BFF转发请求时需保证
Authorization: Bearer <JWT>请求头正确传递,Spring Security默认会从此头提取Token校验。 - 自定义异常处理:如需定制Token无效、过期等场景的返回结果,可在Security配置中添加
AuthenticationEntryPoint和AccessDeniedHandler实现类。
内容的提问来源于stack exchange,提问作者Potinos
相关产品推荐
相关产品推荐

