liveBook · Manning

Request scope

As explained in Spring in Action, Sixth Edition

A Spring bean scope in which a separate bean instance is created for each HTTP request.

Request scope creates a separate Spring bean instance for every HTTP request. It is useful when the bean must read request-specific authentication from the SecurityContext, which is unavailable when application-scoped beans are created. section 8.4

Forwarding the user's access token

An IngredientService bean uses @RequestScope to obtain the current OAuth2 authentication, verify the taco-admin-client registration, extract its access token, and construct a RestIngredientService. That service adds the token as a Bearer Authorization header to each RestTemplate request. section 8.4 section 8.4

@Bean
@RequestScope
public IngredientService ingredientService(
              OAuth2AuthorizedClientService clientService) {
  Authentication authentication = 
          SecurityContextHolder.getContext().getAuthentication();
  
  String accessToken = null;
  
  if (authentication.getClass()
            .isAssignableFrom(OAuth2AuthenticationToken.class)) {
    OAuth2AuthenticationToken oauthToken = 
            (OAuth2AuthenticationToken) authentication;
    String clientRegistrationId = 
            oauthToken.getAuthorizedClientRegistrationId();
    if (clientRegistrationId.equals("taco-admin-client")) {
      OAuth2AuthorizedClient client = 
          clientService.loadAuthorizedClient(
              clientRegistrationId, oauthToken.getName());
      accessToken = client.getAccessToken().getTokenValue();
    }
  }
  return new RestIngredientService(accessToken);
}

Shows the complete @Bean and @RequestScope configuration, including SecurityContext access, client-registration checks, and token extraction. 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;
  }

Shows how the constructed RestIngredientService installs an interceptor that adds the bearer token to outgoing requests. section 8.4

How Spring in Action, Sixth Edition covers it

How deep it goes
Explains bean timing, SecurityContext access, client validation, token extraction, and request interception through complete configuration.
Examples
Demonstrates IngredientService, RestIngredientService, taco-admin-client, bearer authorization headers, and the Taco Cloud API.
What it assumes
Assumes familiarity with Spring beans, HTTP requests, Spring Security authentication, OAuth2 clients, and RestTemplate.
What you can do after
Operate/configure a request-scoped service that forwards the current OAuth2 access token through RestTemplate.
How it connects
Connects request scope with Spring beans, Spring Security, SecurityContext, OAuth2 authentication, access tokens, and RestTemplate.

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.