Programming & Development / April 19, 2025

How to Generate a Bearer Token in Spring Boot and Use It in RestTemplate Calls

Spring Boot bearer token OAuth2 client credentials Spring RestTemplate authentication get access token Spring Boot secure API call Spring Boot Spring RestTemplate bearer token example

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:

  1. Add dependencies
  2. Configure your OAuth2 client
  3. Fetch the token using RestTemplate
  4. 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.



Support Free Content Please Donate

Click here for Donate $2
Comments

No comments yet

Add a new Comment

NUHMAN.COM

Information Technology website for Programming & Development, Web Design & UX/UI, Startups & Innovation, Gadgets & Consumer Tech, Cloud Computing & Enterprise Tech, Cybersecurity, Artificial Intelligence (AI) & Machine Learning (ML), Gaming Technology, Mobile Development, Tech News & Trends, Open Source & Linux, Data Science & Analytics

Categories

Tags

©{" "} Nuhmans.com . All Rights Reserved. Designed by{" "} HTML Codex