liveBook · Manning

Bearer authentication

As explained in Spring in Action, Sixth Edition

An access token presented in an HTTP Authorization header using the Bearer authentication scheme.

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

How Spring in Action, Sixth Edition covers it

How deep it goes
Traces header construction, request interception, request scope, and SecurityContext-based token lookup.
Examples
Demonstrates a RestIngredientService calling Taco Cloud API endpoints with writeIngredients authorization.
What it assumes
Assumes OAuth 2 authorization code flow and Spring Security authentication context knowledge.
What you can do after
Apply it via Spring Security and RestTemplate to send authorized API requests.
How it connects
Connects access tokens with OAuth 2 client, authorization code flow, RestTemplate, and SecurityContext.

Also explained in

Compare how 5 books explain bearer authentication →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Spring in Action, Sixth Edition. The section links point to the parts of the book it draws on.