How to Send a Bearer Token with RestClient
This tutorial explains how to send a Bearer token with
How Bearer token authentication works with
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
Explanation of the code
Setting a default Bearer token on
When calling a third-party service that uses a long-lived API key issued as a Bearer token, configure
Explanation of the code
Sending a dynamic token with a custom
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
Explanation of the code
Automating OAuth2 tokens with
For service-to-service calls that use OAuth2 client credentials, Spring Security provides OAuth2ClientHttpRequestInterceptor through
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
The application on port 8080 trusts JWTs issued by
After starting
OUTPUT of the above code
Explanation of the code
For OAuth2 tokens, prefer Spring Security's
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.
- Scheme prefix: The header value must start with the literal word
Bearerfollowed by a single space and then the token string. - Built-in helper: Calling
HttpHeaders.setBearerAuth(token)writes theAuthorizationheader with the requiredBearerprefix automatically. - Server validation: The protected API validates the token and its scopes, returning
200 OKwhen valid or401 Unauthorizedwith aWWW-Authenticateheader 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 withheaders(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);
headers(h -> h.setBearerAuth(token))is the preferred form because it writes both theAuthorizationheader name and theBearerprefix without manual string concatenation.header(HttpHeaders.AUTHORIZATION, "Bearer " + token)sends the exact same HTTP header using Spring'sHttpHeaders.AUTHORIZATIONconstant.- Neither call alters the shared
RestClientinstance, 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);
defaultHeaders(h -> h.setBearerAuth(staticApiToken))attaches theAuthorizationheader 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);
}
}
- Register the interceptor on a client with
builder.clone().requestInterceptor(new BearerTokenInterceptor(tokenService::getCurrentToken)).build(). - On every call,
intercept()retrieves the current token fromtokenSupplierand writes it withsetBearerAuth(token)before callingexecution.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.
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);
}
}
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);
}
}
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"
SecurityConfigprotects every/api/**path withhasAuthority("SCOPE_books.read")and enables JWT validation viaoauth2ResourceServer(), while leaving/reportopen socurlcan trigger the client calls directly.ClientConfigdefines anAuthorizedClientServiceOAuth2AuthorizedClientManagerso client credentials tokens can be fetched and cached both inside and outside HTTP request threads.OAuth2ClientHttpRequestInterceptoris configured withsetClientRegistrationIdResolver(request -> "reporting")to bind outgoing calls frombooksClientto thereportingclient registration inapplication.properties.- The
booksClientandplainClientbean methods each receive aRestClient.Builderof their own, already holding Spring Boot's auto-configured defaults, so the interceptor ofbooksClientcannot reachplainClient. Thebuilder.clone()calls are a safeguard in case one instance is ever reused. ReportControllercalls/api/bookswithout any authentication boilerplate onbooksClient, and catchesHttpClientErrorExceptiononplainClientto display the401status andWWW-Authenticateresponse header.
- 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 asAuthorization: Bearer ..., and the API accepted the request withreportingas the subject, because client credentials tokens identify the calling application rather than an end user. - The second call to
/reportcarried 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-tokentriggered a401 UNAUTHORIZEDresponse from/api/books. ItsWWW-Authenticateheader 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 toRestClient 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 |
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 onRestClient.Builderstays frozen for the lifetime of the client and causes401failures 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
OAuth2AuthorizedClientManageroutside web requests: Spring Security's default manager depends on an active HTTP servlet request. For scheduled jobs, message listeners, or startup routines, define anAuthorizedClientServiceOAuth2AuthorizedClientManagerbean as shown inClientConfig. - Missing
RestClient.Builderbean in Spring Boot 4: In Spring Boot 4, theRestClient.Builderbean is provided byspring-boot-starter-restclient. Without that starter on the classpath, injecting the builder fails withrequired a bean of type 'org.springframework.web.client.RestClient$Builder' that could not be found. - Reusing one
RestClient.Builderinstance 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, callbuilder.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
Authorizationheader 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 theAuthorization: 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.