Return to site

🔐🌱 IMPLEMENTING A SPRING OAUTH2 CLIENT FOR API CALLS

· spring

Your Spring Boot application needs to call a protected API.

You could manually request an access token, store it, check its expiration and add an Authorization header…

Or let Spring Security manage the OAuth2 lifecycle. 🚀

This example uses the Client Credentials grant, designed for service-to-service communication without an end user.

Start by adding:

spring-boot-starter-oauth2-client

🔸 TLDR

▪️ Configure the OAuth2 provider and client registration.

▪️ Add OAuth2ClientHttpRequestInterceptor to RestClient.

▪️ Select the registration when calling the protected API.

▪️ Let Spring manage token acquisition and renewal.

Section image

🔸 1. REGISTER THE OAUTH2 CLIENT

spring:
 security:
 oauth2:
 client:
 registration:
 inventory:
 client-id: ${INVENTORY_CLIENT_ID}
 client-secret: ${INVENTORY_CLIENT_SECRET}
 authorization-grant-type: client_credentials
 scope: inventory.read
 provider:
 inventory:
 token-uri: https://auth.example.com/oauth2/token

The registration describes how the application authenticates.

Keep credentials outside the repository using environment variables or a secret manager.

🔸 2. CONNECT OAUTH2 TO RESTCLIENT

@Bean
RestClient inventoryClient(
 RestClient.Builder builder,
 OAuth2AuthorizedClientManager clientManager) {
 var oauth2 =
 new OAuth2ClientHttpRequestInterceptor(clientManager);
 return builder
 .baseUrl("https://api.example.com")
 .requestInterceptor(oauth2)
 .build();
}

The interceptor connects RestClient to Spring Security.

It can obtain an access token, renew it when necessary and attach it as:

Authorization: Bearer

Your business code does not need to manage tokens manually.

🔸 3. CALL THE PROTECTED API

import static org.springframework.security.oauth2.client
 .web.client.RequestAttributeClientRegistrationIdResolver
 .clientRegistrationId;
Product findProduct(long id) {
 return inventoryClient.get()
 .uri("/products/{id}", id)
 .attributes(clientRegistrationId("inventory"))
 .retrieve()
 .body(Product.class);
}

The clientRegistrationId selects the inventory configuration.

Before sending the request, Spring obtains the appropriate token and adds it to the HTTP request.

🔸 TAKEAWAYS

▪️ An OAuth2 client calls protected resources.

▪️ A Resource Server protects incoming requests—these are different roles.

▪️ client_credentials represents the application, not a logged-in user.

▪️ Never commit client secrets to source control.

▪️ Keep authentication plumbing outside your business logic.

#Java #SpringBoot #SpringSecurity #OAuth2 #RestClient #APISecurity #BackendDevelopment #Microservices

Go further with Java certification:

Java👇

Spring👇

SpringBook👇

JavaBook👇