【问题标题】:Spring Boot: Calling an OAuth2 protected REST serviceSpring Boot:调用受 OAuth2 保护的 REST 服务
【发布时间】:2020-10-31 04:27:15
【问题描述】:

我有一个使用 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()
    }
}

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

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

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

java.lang.IllegalArgumentException: Invalid Authorization Grant Type (client_credentials) for Client Registration with Id: test

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

【问题讨论】:

  • 只是我的 2 美分...将提供商从 sniac 重命名为 test
  • @bilak 这是我的错字!我将提供程序重命名为“测试”只是为了发布,所以这实际上不是问题。不过还是谢谢你!

标签: java spring spring-boot kotlin oauth-2.0


【解决方案1】:

这对我有用:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-27
    • 1970-01-01
    • 2019-09-05
    • 2016-04-29
    • 2015-03-23
    • 2015-11-30
    • 2021-01-01
    • 2023-03-11
    相关资源
    最近更新 更多