When you're calling a secured API from a Spring Boot application, you'll often need a Bearer Token obtained via OAuth2 client credentials flow. This guide walks you through the entire setup:
- Add dependencies
- Configure your OAuth2 client
- Fetch the token using
RestTemplate
- Attach it to your API requests
🧱 1. Add Required Dependencies
Maven
xml
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
⚙️ 2. Configure OAuth2 Client
application.yml
yaml
spring:
security:
oauth2:
client:
registration:
my-client:
client-id: your-client-id
client-secret: your-client-secret
authorization-grant-type: client_credentials
scope: read,write
provider:
my-provider:
token-uri: https://auth-server.com/oauth/token
🔐 3. Generate Bearer Token Programmatically
java
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.core.ParameterizedTypeReference;
import java.util.Map;
@Service
public class OAuth2TokenService {
private final RestTemplate restTemplate = new RestTemplate();
public String getBearerToken() {
String tokenUri = "https://auth-server.com/oauth/token";
String clientId = "your-client-id";
String clientSecret = "your-client-secret";
// Create headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
headers.setBasicAuth(clientId, clientSecret);
// Create body
MultiValueMap<String, String> body = new LinkedMultiValueMap<>();
body.add("grant_type", "client_credentials");
HttpEntity<MultiValueMap<String, String>> request = new HttpEntity<>(body, headers);
ResponseEntity<Map<String, String>> response = restTemplate.exchange(
tokenUri,
HttpMethod.POST,
request,
new ParameterizedTypeReference<>() {}
);
return response.getBody().get("access_token");
}
}
🌐 4. Make API Call with Bearer Token
java
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class ApiService {
private final RestTemplate restTemplate = new RestTemplate();
private final OAuth2TokenService tokenService;
public ApiService(OAuth2TokenService tokenService) {
this.tokenService = tokenService;
}
public String callProtectedApi() {
String url = "https://api.example.com/resource";
String token = tokenService.getBearerToken();
HttpHeaders headers = new HttpHeaders();
headers.setBearerAuth(token);
HttpEntity<String> request = new HttpEntity<>(headers);
ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, request, String.class);
return response.getBody();
}
}
✅ Summary
- Uses Client Credentials OAuth2 flow
- Token fetched manually using
RestTemplate
- Included in subsequent API requests via
Authorization: Bearer <token>
- Easily extensible for retry logic or caching tokens
🚀 Bonus Tips:
- Want to automatically manage tokens? Use
WebClient
with Spring Security's OAuth2AuthorizedClientManager
. - If you're calling multiple services, consider caching the token to avoid fetching it for every request.
- Add logging for token failures and API responses for better observability.