Spring Boot:调用 OAuth2 保护的 REST 服务

sen*_*t_6 5 java spring oauth-2.0 kotlin spring-boot

我有一个使用 Spring Boot 构建的现有 REST API。在服务层的一个函数中,我需要调用受 OAuth2(客户端凭据)保护的外部 REST 服务。

使用 Spring Boot 2.3,我意识到OAuth2RestTemplate它已被弃用,所以我选择使用WebClient.

按照本教程 - https://www.baeldung.com/spring-webclient-oauth2,我现在的WebClientConfig课程如下:

@Configuration
class WebClientConfig {    
    @Bean
    fun webClient(
            clientRegistrations: ClientRegistrationRepository?,
            authorizedClients: OAuth2AuthorizedClientRepository?): WebClient? {
        val oauth2 = ServletOAuth2AuthorizedClientExchangeFilterFunction(clientRegistrations, authorizedClients)
        oauth2.setDefaultOAuth2AuthorizedClient(false)
        oauth2.setDefaultClientRegistrationId("test")
        return WebClient.builder()
                .apply(oauth2.oauth2Configuration())
                .build()
    }
}
Run Code Online (Sandbox Code Playgroud)

在我的属性文件中,我有:

spring:
  security:
    oauth2:
      client:
        registration:
          test:
            client-id: <redacted>
            client-secret: <redacted>
            authorization-grant-type: client_credentials
        provider:
          test:
            token-uri: <redacted>
Run Code Online (Sandbox Code Playgroud)

我什至无法判断这是否有效,因为在访问与此 OAuth2 身份验证无关的 API 上的不同端点时,我不断收到以下错误:

java.lang.IllegalArgumentException: Invalid Authorization Grant Type (client_credentials) for Client Registration with Id: test
Run Code Online (Sandbox Code Playgroud)

我束手无策,因为我无法克服这个问题......任何帮助将不胜感激!谢谢!

bil*_*lak 2

这对我有用:

  @Bean
  public WebClient webClient(OAuth2AuthorizedClientManager authorizedClientManager) {
    ServletOAuth2AuthorizedClientExchangeFilterFunction oauth2Client = new ServletOAuth2AuthorizedClientExchangeFilterFunction(
        authorizedClientManager);
    oauth2Client.setDefaultClientRegistrationId("test");

    return WebClient.builder()
        .apply(oauth2Client.oauth2Configuration())
        .build();
  }

  @Bean
  public OAuth2AuthorizedClientManager authorizedClientManager(
      ClientRegistrationRepository clientRegistrationRepository,
      OAuth2AuthorizedClientRepository authorizedClientRepository) {

    OAuth2AuthorizedClientProvider authorizedClientProvider = OAuth2AuthorizedClientProviderBuilder.builder()
        .refreshToken()
        .clientCredentials()
        .build();

    DefaultOAuth2AuthorizedClientManager authorizedClientManager = new DefaultOAuth2AuthorizedClientManager(
        clientRegistrationRepository, authorizedClientRepository);
    authorizedClientManager.setAuthorizedClientProvider(authorizedClientProvider);

    return authorizedClientManager;
  }
Run Code Online (Sandbox Code Playgroud)