How to Send a Bearer Token with RestClient

This tutorial explains how to send a Bearer token with RestClient, the synchronous client that replaces RestTemplate in new Spring Boot code, when calling APIs protected by OAuth2 or JWT. It covers, in this order, how Bearer token authentication works over HTTP, attaching a token on a single request, configuring a static default token on RestClient.Builder, injecting a dynamic token with a custom ClientHttpRequestInterceptor, automating token acquisition and renewal with Spring Security's OAuth2ClientHttpRequestInterceptor in a complete two-application example, comparing all four approaches, and common pitfalls to avoid. The complete OAuth2 example in this tutorial was tested on Spring Boot 4.1.2, Spring Framework 7.0.10, Spring Security 7.1.2, and JDK 25.

How Bearer token authentication works with RestClient

A Bearer token is an opaque string or JSON Web Token (JWT) that grants access to a protected resource to whichever client presents it. An API protected by OAuth2 or JWT expects every request to carry the Authorization header in the format Authorization: Bearer <token>, and answers 401 Unauthorized to any request sent without a valid token. With RestClient, Spring's HttpHeaders API provides built-in support for formatting this header cleanly, and Spring Security can also fetch, cache, and renew OAuth2 tokens automatically.

Diagram showing how Spring RestClient sends a Bearer token in the HTTP Authorization header
  • Scheme prefix: The header value must start with the literal word Bearer followed by a single space and then the token string.
  • Built-in helper: Calling HttpHeaders.setBearerAuth(token) writes the Authorization header with the required Bearer prefix automatically.
  • Server validation: The protected API validates the token and its scopes, returning 200 OK when valid or 401 Unauthorized with a WWW-Authenticate header when missing or rejected.

Sending a Bearer token on a single request

When the token is already known at the call site, for example when forwarding an incoming request's token to a downstream service, attach it directly to the individual request with headers(h -> h.setBearerAuth(token)). For an introduction to building and calling endpoints with RestClient, see RestClient and HTTP interface clientsClick to read tutorial: Calling REST Services with RestClient and HTTP Interfaces.

Sending a Bearer token per request
// Preferred: uses HttpHeaders.setBearerAuth()
String body = restClient.get()
    .uri("/api/books")
    .headers(h -> h.setBearerAuth(token))   // Authorization: Bearer <token>
    .retrieve()
    .body(String.class);

// Equivalent: sets the raw Authorization header directly
String bodyWithRawHeader = restClient.get()
    .uri("/api/books")
    .header(HttpHeaders.AUTHORIZATION, "Bearer " + token)
    .retrieve()
    .body(String.class);
Explanation of the code
  • headers(h -> h.setBearerAuth(token)) is the preferred form because it writes both the Authorization header name and the Bearer prefix without manual string concatenation.
  • header(HttpHeaders.AUTHORIZATION, "Bearer " + token) sends the exact same HTTP header using Spring's HttpHeaders.AUTHORIZATION constant.
  • Neither call alters the shared RestClient instance, so the header applies only to that single request and must be supplied again on subsequent calls.

Setting a default Bearer token on RestClient.Builder

When calling a third-party service that uses a long-lived API key issued as a Bearer token, configure defaultHeaders() on RestClient.Builder so every request made by the built client carries the token automatically.

Configuring a static Bearer token on RestClient.Builder
RestClient restClient = builder.clone()
    .baseUrl("https://api.example.com")
    .defaultHeaders(h -> h.setBearerAuth(staticApiToken))
    .build();

String body = restClient.get()
    .uri("/api/books")
    .retrieve()
    .body(String.class);
Explanation of the code
  • defaultHeaders(h -> h.setBearerAuth(staticApiToken)) attaches the Authorization header once when the client is constructed and sends it on every subsequent call.
  • Spring Boot hands every injection point a new RestClient.Builder, so beans do not share one. builder.clone() matters when the same builder instance builds more than one client: the default header then stays on this client only.
  • Because the token is fixed when build() runs, this approach is unsuitable for short-lived tokens that expire.

Sending a dynamic token with a custom ClientHttpRequestInterceptor

If tokens expire and come from a non-OAuth2 source, such as a vendor's custom login endpoint, implement Spring's ClientHttpRequestInterceptor interface. The interceptor runs before each outgoing request, obtains the latest token from a Supplier<String>, and attaches it to the request headers.

BearerTokenInterceptor.java - reusable interceptor for non-OAuth2 token sources
//BearerTokenInterceptor.java
package com.javabrahman.tips.bearer;

import java.io.IOException;
import java.util.Objects;
import java.util.function.Supplier;
import org.springframework.http.HttpRequest;
import org.springframework.http.client.ClientHttpRequestExecution;
import org.springframework.http.client.ClientHttpRequestInterceptor;
import org.springframework.http.client.ClientHttpResponse;

public class BearerTokenInterceptor implements ClientHttpRequestInterceptor {

  private final Supplier<String> tokenSupplier;

  public BearerTokenInterceptor(Supplier<String> tokenSupplier) {
    this.tokenSupplier = Objects.requireNonNull(tokenSupplier, "tokenSupplier must not be null");
  }

  @Override
  public ClientHttpResponse intercept(
      HttpRequest request,
      byte[] body,
      ClientHttpRequestExecution execution) throws IOException {
    String token = tokenSupplier.get();
    if (token != null && !token.isBlank()) {
      request.getHeaders().setBearerAuth(token);
    }
    return execution.execute(request, body);
  }
}
Explanation of the code
  • Register the interceptor on a client with builder.clone().requestInterceptor(new BearerTokenInterceptor(tokenService::getCurrentToken)).build().
  • On every call, intercept() retrieves the current token from tokenSupplier and writes it with setBearerAuth(token) before calling execution.execute(request, body).
  • With a custom interceptor, caching the token in memory and refreshing it before expiry remains the responsibility of your own token service.

Automating OAuth2 tokens with OAuth2ClientHttpRequestInterceptor

For service-to-service calls that use OAuth2 client credentials, Spring Security provides OAuth2ClientHttpRequestInterceptor through spring-boot-starter-oauth2-client. When attached to a RestClient, it requests an access token from the authorization server on the first call, caches and reuses that token until shortly before expiry, and obtains a fresh token automatically when needed.

Diagram showing OAuth2ClientHttpRequestInterceptor fetching, caching, and attaching an OAuth2 Bearer token for RestClient The complete working example below uses two Spring Boot applications. The authorization server runs on port 9000 using Spring Authorization Server configured purely through properties, and defines a client named reporting allowed to request tokens with the books.read scope. The second application runs on port 8080 and acts as both the protected API and the caller to keep the setup compact: its /api/books endpoint requires a JWT with scope books.read, while its /report endpoints call /api/books via RestClient, once through OAuth2ClientHttpRequestInterceptor and once without any token. For a detailed walkthrough of the resource server side, see Spring Security OAuth2 resource server with JWTClick to read tutorial: Spring Security OAuth2 Resource Server with JWT.

tokenserver.properties - the authorization server
server.port=9000
spring.security.oauth2.authorizationserver.issuer=http://127.0.0.1:9000
spring.security.oauth2.authorizationserver.client.reporting.registration.client-id=reporting
spring.security.oauth2.authorizationserver.client.reporting.registration.client-secret={noop}reporting-secret
spring.security.oauth2.authorizationserver.client.reporting.registration.client-authentication-methods=client_secret_basic
spring.security.oauth2.authorizationserver.client.reporting.registration.authorization-grant-types=client_credentials
spring.security.oauth2.authorizationserver.client.reporting.registration.scopes=books.read
TokenServerApp.java - the authorization server
//TokenServerApp.java
package com.javabrahman.tips.tokenserver;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class TokenServerApp {

  public static void main(String[] args) {
    SpringApplication.run(TokenServerApp.class, args);
  }
}
The application on port 8080 trusts JWTs issued by http://127.0.0.1:9000 and registers itself as the OAuth2 client reporting.

src/main/resources/application.properties
spring.main.banner-mode=off
logging.level.root=WARN
# as an API: accept tokens issued by the authorization server
spring.security.oauth2.resourceserver.jwt.issuer-uri=http://127.0.0.1:9000
# as a client: obtain tokens from it with the client credentials grant
spring.security.oauth2.client.registration.reporting.client-id=reporting
spring.security.oauth2.client.registration.reporting.client-secret=reporting-secret
spring.security.oauth2.client.registration.reporting.authorization-grant-type=client_credentials
spring.security.oauth2.client.registration.reporting.scope=books.read
spring.security.oauth2.client.provider.reporting.issuer-uri=http://127.0.0.1:9000
SecurityConfig.java
//SecurityConfig.java
package com.javabrahman.tips.bearer;

import static org.springframework.security.config.Customizer.withDefaults;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.web.SecurityFilterChain;

@Configuration
public class SecurityConfig {

  @Bean
  SecurityFilterChain security(HttpSecurity http) throws Exception {
    http
        .authorizeHttpRequests(auth -> auth
            .requestMatchers("/api/**").hasAuthority("SCOPE_books.read")   // the API needs a token
            .anyRequest().permitAll())                                     // the /report endpoints do not
        .oauth2ResourceServer(oauth2 -> oauth2.jwt(withDefaults()))
        .sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
        .csrf(csrf -> csrf.disable());
    return http.build();
  }
}
BooksApi.java - the protected API
//BooksApi.java
package com.javabrahman.tips.bearer;

import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class BooksApi {

  @GetMapping("/api/books")
  public Map<String, Object> books(@AuthenticationPrincipal Jwt token) {
    Map<String, Object> answer = new LinkedHashMap<>();
    answer.put("books", List.of("Effective Java", "Clean Code"));
    answer.put("calledBy", token.getSubject());
    answer.put("tokenEndsWith", token.getTokenValue().substring(token.getTokenValue().length() - 8));
    answer.put("tokenExpiresAt", token.getExpiresAt());
    return answer;
  }
}
ClientConfig.java - a RestClient that sends OAuth2 tokens
//ClientConfig.java
package com.javabrahman.tips.bearer;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.oauth2.client.AuthorizedClientServiceOAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientManager;
import org.springframework.security.oauth2.client.OAuth2AuthorizedClientService;
import org.springframework.security.oauth2.client.registration.ClientRegistrationRepository;
import org.springframework.security.oauth2.client.web.client.OAuth2ClientHttpRequestInterceptor;
import org.springframework.web.client.RestClient;

@Configuration
public class ClientConfig {

  // obtains client credentials tokens and keeps them until they expire - also outside of web requests
  @Bean
  OAuth2AuthorizedClientManager authorizedClientManager(ClientRegistrationRepository registrations,
      OAuth2AuthorizedClientService authorizedClients) {
    return new AuthorizedClientServiceOAuth2AuthorizedClientManager(registrations, authorizedClients);
  }

  @Bean
  RestClient booksClient(RestClient.Builder builder, OAuth2AuthorizedClientManager manager) {
    OAuth2ClientHttpRequestInterceptor oauth2 = new OAuth2ClientHttpRequestInterceptor(manager);
    oauth2.setClientRegistrationIdResolver(request -> "reporting");   // which registration's token to send
    return builder.clone().baseUrl("http://localhost:8080").requestInterceptor(oauth2).build();
  }

  @Bean
  RestClient plainClient(RestClient.Builder builder) {
    return builder.clone().baseUrl("http://localhost:8080").build();
  }
}
ReportController.java - the calls
//ReportController.java
package com.javabrahman.tips.bearer;

import java.util.Map;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.HttpClientErrorException;
import org.springframework.web.client.RestClient;

@RestController
public class ReportController {

  private final RestClient booksClient;
  private final RestClient plainClient;

  public ReportController(@Qualifier("booksClient") RestClient booksClient, @Qualifier("plainClient") RestClient plainClient) {
    this.booksClient = booksClient;
    this.plainClient = plainClient;
  }

  @GetMapping("/report")
  public Map<?, ?> report() {
    return booksClient.get().uri("/api/books").retrieve().body(Map.class);
  }

  @GetMapping("/report/without-token")
  public String reportWithoutToken() {
    try {
      return plainClient.get().uri("/api/books").retrieve().body(String.class);
    } catch (HttpClientErrorException e) {
      return "the API answered " + e.getStatusCode() + ", WWW-Authenticate: " + e.getResponseHeaders().getFirst("WWW-Authenticate");
    }
  }
}
ReportApp.java
//ReportApp.java
package com.javabrahman.tips.bearer;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ReportApp {

  public static void main(String[] args) {
    SpringApplication.run(ReportApp.class, args);
  }
}
After starting TokenServerApp first and then ReportApp, calling /report twice and /report/without-token once produces the output below. BooksApi echoes the trailing characters and expiry timestamp of the received JWT so the two authenticated calls can be compared.

OUTPUT of the above code
> curl -i http://localhost:8080/report
HTTP/1.1 200
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Pragma: no-cache
X-Frame-Options: DENY
Cache-Control: no-store, must-revalidate, no-cache, max-age=0
Content-Length: 131
Content-Type: application/json
Expires: 0

{"books":["Effective Java","Clean Code"],"calledBy":"reporting","tokenEndsWith":"HlNPx_bA","tokenExpiresAt":"2026-11-15T09:48:08Z"}

> curl -i http://localhost:8080/report
HTTP/1.1 200
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Pragma: no-cache
X-Frame-Options: DENY
Cache-Control: no-store, must-revalidate, no-cache, max-age=0
Content-Length: 131
Content-Type: application/json
Expires: 0

{"books":["Effective Java","Clean Code"],"calledBy":"reporting","tokenEndsWith":"HlNPx_bA","tokenExpiresAt":"2026-11-15T09:48:08Z"}

> curl -i http://localhost:8080/report/without-token
HTTP/1.1 200
X-Content-Type-Options: nosniff
X-XSS-Protection: 0
Pragma: no-cache
X-Frame-Options: DENY
Cache-Control: no-store, must-revalidate, no-cache, max-age=0
Content-Length: 138
Content-Type: text/plain; charset=UTF-8
Expires: 0

the API answered 401 UNAUTHORIZED, WWW-Authenticate: Bearer resource_metadata="http://localhost:8080/.well-known/oauth-protected-resource"
Explanation of the code
  • SecurityConfig protects every /api/** path with hasAuthority("SCOPE_books.read") and enables JWT validation via oauth2ResourceServer(), while leaving /report open so curl can trigger the client calls directly.
  • ClientConfig defines an AuthorizedClientServiceOAuth2AuthorizedClientManager so client credentials tokens can be fetched and cached both inside and outside HTTP request threads.
  • OAuth2ClientHttpRequestInterceptor is configured with setClientRegistrationIdResolver(request -> "reporting") to bind outgoing calls from booksClient to the reporting client registration in application.properties.
  • The booksClient and plainClient bean methods each receive a RestClient.Builder of their own, already holding Spring Boot's auto-configured defaults, so the interceptor of booksClient cannot reach plainClient. The builder.clone() calls are a safeguard in case one instance is ever reused.
  • ReportController calls /api/books without any authentication boilerplate on booksClient, and catches HttpClientErrorException on plainClient to display the 401 status and WWW-Authenticate response header.
Explanation of the output
  • On the first call to /report, the interceptor had no cached token. It requested one from the authorization server using the configured client ID and secret, sent it as Authorization: Bearer ..., and the API accepted the request with reporting as the subject, because client credentials tokens identify the calling application rather than an end user.
  • The second call to /report carried the exact same trailing token characters and expiry timestamp, confirming that the interceptor reused its cached token. It requests a fresh token automatically shortly before expiry, which defaults to five minutes in Spring Authorization Server.
  • Calling /report/without-token triggered a 401 UNAUTHORIZED response from /api/books. Its WWW-Authenticate header points to the API's protected resource metadata endpoint, which Spring Security 7 publishes so clients can discover which authorization server issues tokens for the API.

Comparing the four approaches

The table below summarizes when to use each method for attaching a Bearer token to RestClient requests and the main limits of each option.

Approach When to use it Limits
headers(h -> h.setBearerAuth(token)) on a request The token is already known at the call site, i.e. forwarding an incoming request's token to a downstream service Must be repeated on every call
defaultHeaders(h -> h.setBearerAuth(token)) on the builder A long-lived API key issued as a Bearer token Fixed when the client is built; does not handle expiring tokens
Custom ClientHttpRequestInterceptor Expiring tokens from a non-OAuth2 source, such as a vendor's login endpoint Token caching and renewal must be implemented in application code
Spring Security's OAuth2ClientHttpRequestInterceptor Service-to-service calls using OAuth2 client credentials Requires spring-boot-starter-oauth2-client and a client registration
For OAuth2 tokens, prefer Spring Security's OAuth2ClientHttpRequestInterceptor so that token acquisition, caching, and renewal before expiry are handled automatically without custom token-management code.

Common pitfalls to avoid

  • Storing an expiring token in defaultHeaders(): A token configured on RestClient.Builder stays frozen for the lifetime of the client and causes 401 failures as soon as it expires, i.e. after five minutes with Spring Authorization Server's default lifetime. Expiring tokens belong in an interceptor.
  • Using the default OAuth2AuthorizedClientManager outside web requests: Spring Security's default manager depends on an active HTTP servlet request. For scheduled jobs, message listeners, or startup routines, define an AuthorizedClientServiceOAuth2AuthorizedClientManager bean as shown in ClientConfig.
  • Missing RestClient.Builder bean in Spring Boot 4: In Spring Boot 4, the RestClient.Builder bean is provided by spring-boot-starter-restclient. Without that starter on the classpath, injecting the builder fails with required a bean of type 'org.springframework.web.client.RestClient$Builder' that could not be found.
  • Reusing one RestClient.Builder instance for several clients: Interceptors and default headers stay on a builder and go into every client built from it afterwards. When one instance builds more than one client, call builder.clone() before adding credentials, so they do not leak onto unauthenticated clients.
  • Leaking Bearer tokens into logs or plain HTTP: Always transmit Bearer tokens over HTTPS in production, and exclude the Authorization header from any request-logging filter or interceptor, because anyone with access to the logs can reuse the token until it expires.

Summary

This tutorial explained how Bearer token authentication uses the Authorization: Bearer <token> HTTP header and how RestClient supports it. It covered sending a token per request with setBearerAuth() and header(), setting a static token via defaultHeaders() on RestClient.Builder, writing a custom ClientHttpRequestInterceptor for non-OAuth2 sources, automating OAuth2 client credentials with Spring Security's OAuth2ClientHttpRequestInterceptor in a two-application example, comparing all four approaches, and avoiding common configuration and security pitfalls.