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

5

我有一个使用Spring Boot构建的现有REST API。在服务层中的其中一个函数上,我需要调用一个受OAuth2(client-credentials)保护的外部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()
    }
}

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

spring:
  security:
    oauth2:
      client:
        registration:
          test:
            client-id: <redacted>
            client-secret: <redacted>
            authorization-grant-type: client_credentials
        provider:
          test:
            token-uri: <redacted>

我甚至无法确定这是否有效,因为当我访问与此OAuth2身份验证无关的API上的不同端点时,会不断收到以下错误提示:
java.lang.IllegalArgumentException: Invalid Authorization Grant Type (client_credentials) for Client Registration with Id: test

我快要崩溃了,因为我无法解决这个问题...任何帮助将不胜感激!谢谢!


1
只是我的个人意见...将提供者从sniac重命名为test - bilak
@bilak,那是我的笔误!我只是为了发布帖子而将提供程序重命名为“test”,所以那不会是问题。但还是谢谢你! - sentient_6
1个回答

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;
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接