微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用 oAuth2 调用外部 API

如何解决使用 oAuth2 调用外部 API

我需要从我的 Spring Boot 项目中调用外部 API。 外部 API 使用 client_credentials 使用 OAuth 2 安全身份验证。 我有客户端 ID 和密钥。可以使用RestTemplate吗? 您能否建议如何将 ID 和密钥作为 API 调用的一部分传递?有什么例子吗?

解决方法

您也可以使用 RestTemplate,但我建议 WebClient 会更好,因为它是反应式和异步的,并且 RestTemplate 可能会折旧以备将来使用(可能不会太多)。

请参考https://www.baeldung.com/spring-webclient-oauth2

@Autowired
WebClient client;

public Mono<String> obtainSecuredResource() {
    String encodedClientData = 
      Base64Utils.encodeToString("bael-client-id:bael-secret".getBytes());
    Mono<String> resource = client.post()
      .uri("localhost:8085/oauth/token")
      .header("Authorization","Basic " + encodedClientData)
      .body(BodyInserters.fromFormData("grant_type","client_credentials"))
      .retrieve()
      .bodyToMono(JsonNode.class)
      .flatMap(tokenResponse -> {
          String accessTokenValue = tokenResponse.get("access_token")
            .textValue();
          return client.get()
            .uri("localhost:8084/retrieve-resource")
            .headers(h -> h.setBearerAuth(accessTokenValue))
            .retrieve()
            .bodyToMono(String.class);
        });
    return resource.map(res ->
      "Retrieved the resource using a manual approach: " + res);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。