问题描述
我需要从我的 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);
}