Bearer authentication sends an access token in the HTTP Authorization header as "Bearer" followed by the token value. A protected API can then authorize the request using the token’s scopes, such as writeIngredients. section 8.4
A Spring application connects the token to outgoing REST requests by:
- Passing the access token into a RestTemplate-based client. section 8.4
- Adding an interceptor that appends the Authorization header to every request. section 8.4
- Creating the service per request so it can read authentication from the SecurityContext. section 8.4
public RestIngredientService(String accessToken) {
this.restTemplate = new RestTemplate();
if (accessToken != null) {
this.restTemplate
.getInterceptors()
.add(getBearerTokenInterceptor(accessToken));
}
}
private ClientHttpRequestInterceptor
getBearerTokenInterceptor(String accessToken) {
ClientHttpRequestInterceptor interceptor =
new ClientHttpRequestInterceptor() {
@Override
public ClientHttpResponse intercept(
HttpRequest request, byte[] bytes,
ClientHttpRequestExecution execution) throws IOException {
request.getHeaders().add("Authorization", "Bearer " + accessToken);
return execution.execute(request, bytes);
}
};
return interceptor;
}
Inspect the interceptor that formats the Bearer header and attaches it to outgoing RestTemplate requests. section 8.4




