Spring Security 6中修改Oauth2认证服务器请求体参数名
解决Spring Boot 3.1.4 OAuth2资源服务器Opaque令牌校验参数名修改问题
核心思路
要修改opaque令牌校验请求的参数名,需自定义OpaqueTokenIntrospector实现,替换默认的请求体构造逻辑,将参数名从token改为xtoken。
具体实现步骤
- 自定义OpaqueTokenIntrospector
继承默认的NimbusOpaqueTokenIntrospector,重写构建请求的方法,替换参数名:
import org.springframework.security.oauth2.core.OAuth2TokenIntrospectionClaimNames; import org.springframework.security.oauth2.server.resource.introspection.NimbusOpaqueTokenIntrospector; import org.springframework.security.oauth2.server.resource.introspection.OAuth2IntrospectionException; import com.nimbusds.oauth2.sdk.http.HTTPRequest; import com.nimbusds.oauth2.sdk.http.HTTPResponse; import com.nimbusds.oauth2.sdk.token.OAuth2Token; import java.io.IOException; import java.net.URI; import java.util.Collections; public class CustomOpaqueTokenIntrospector extends NimbusOpaqueTokenIntrospector { public CustomOpaqueTokenIntrospector(URI introspectionUri, String clientId, String clientSecret) { super(introspectionUri, clientId, clientSecret); } @Override protected HTTPResponse makeRequest(OAuth2Token token) throws IOException, OAuth2IntrospectionException { HTTPRequest request = new HTTPRequest(HTTPRequest.Method.POST, getIntrospectionUri()); // 将参数名替换为"xtoken" request.setQueryParameters(Collections.singletonMap("xtoken", token.getValue())); // 保留客户端认证逻辑 applyClientAuthentication(request); return request.send(); } }
- 配置SecurityFilterChain
在安全配置类中,替换默认的令牌解析器为自定义实现:
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 java.net.URI; @Configuration @EnableWebSecurity public class SecurityConfig { @Bean public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { http .authorizeHttpRequests(auth -> auth .anyRequest().authenticated() ) .oauth2ResourceServer(oauth2 -> oauth2 .opaqueToken(token -> token .introspector(customOpaqueTokenIntrospector()) ) ); return http.build(); } @Bean public CustomOpaqueTokenIntrospector customOpaqueTokenIntrospector() { // 替换为你的认证服务器校验地址、客户端ID和密钥 URI introspectionUri = URI.create("https://your-auth-server.com/oauth2/introspect"); String clientId = "your-client-id"; String clientSecret = "your-client-secret"; return new CustomOpaqueTokenIntrospector(introspectionUri, clientId, clientSecret); } }
- 依赖确认
确保项目已引入Spring Security OAuth2资源服务器依赖:
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'
验证说明
自定义的makeRequest方法会构造包含xtoken参数的POST请求发送至认证服务器,替代默认的token参数,从而解决400 BAD_REQUEST问题。
内容的提问来源于stack exchange,提问作者Notrome
相关产品推荐
相关产品推荐

