如果您需要修改OAuth2请求中的参数名称,您需要配置一个 OAuth2AuthorizedClientProvider
bean。您可以使用 DefaultOAuth2AuthorizedClientProvider
类作为基础,并在其上修改所需的参数名称。例如,以下代码片段将 authorizationCode
的参数名称更改为 custom_code
:
@Configuration @EnableOAuth2Client public class OAuth2Configuration { @Bean public OAuth2AuthorizedClientManager authorizedClientManager( ClientRegistrationRepository clientRegistrationRepository, OAuth2AuthorizedClientRepository authorizedClientRepository) { DefaultOAuth2AuthorizedClientManager authorizedClientManager = new DefaultOAuth2AuthorizedClientManager( clientRegistrationRepository, authorizedClientRepository); DefaultOAuth2AuthorizedClientProvider authorizedClientProvider = new DefaultOAuth2AuthorizedClientProvider(); authorizedClientProvider.setAuthorizationCodeTokenResponseClient( new OAuth2AuthorizationCodeGrantRequestEntityConverter() { @Override public RequestEntity<?> convert(OAuth2AuthorizationCodeGrantRequest request) { HttpHeaders headers = new HttpHeaders(); headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED); MultiValueMap<String, String> parameters = new LinkedMultiValueMap<>(); parameters.add("client_id", request.getClientId()); parameters.add("custom_code", request.getAuthorizationCode()); ... // 添加其它参数 ... return new RequestEntity<>(parameters, headers, HttpMethod.POST, request.getAccessTokenUri()); } }); authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider); return authorizedClientManager; } }
这个例子使用 DefaultOAuth2AuthorizedClientProvider
和 DefaultOAuth2AuthorizedClientManager
类。然后,它使用匿名内部类重写了 OAuth2AuthorizationCodeGrantRequestEntityConverter
类。在 convert()
方法中,我们可以设置任何要发送到授权服务器的参数,包括更改 authorizationCode
参数的名称为 custom_code
。