liveBook · Manning

Request interceptor

As explained in Spring in Action, Sixth Edition

A component that intercepts outgoing client requests to modify them before transmission.

A request interceptor is a component that runs before an outgoing client request is transmitted, allowing it to modify the request. With Spring's RestTemplate, it can add an OAuth 2 bearer token to every API call. section 8.4

Adding a bearer token

A RestIngredientService receives an access token, creates a RestTemplate, and registers an interceptor. The interceptor adds an Authorization header whose value is Bearer followed by the token, then continues execution. This lets protected POST requests reach the API with the required writeIngredients scope. section 8.4

<dependency>
  <groupId>org.springframework.boot</groupId>
  <artifactId>spring-boot-starter-oauth2-client</artifactId>
</dependency>

Add the Spring Boot OAuth 2 client dependency before configuring token-aware request handling. section 8.4

@Bean
SecurityFilterChain defaultSecurityFilterChain(HttpSecurity http) throws Exception {
  http
    .authorizeRequests(
        authorizeRequests -> authorizeRequests.anyRequest().authenticated()
    )
    .oauth2Login(
      oauth2Login -> 
      oauth2Login.loginPage("/oauth2/authorization/taco-admin-client"))
    .oauth2Client(withDefaults());
  return http.build();
}

Enable OAuth 2 client support in the security filter chain so authorized client information is available. section 8.4

How Spring in Action, Sixth Edition covers it

How deep it goes
Explains interceptor registration and header mutation, then connects token retrieval to request-scoped bean creation; it stops short of broader interceptor design.
Examples
Uses RestIngredientService to add a bearer token before calling protected ingredient endpoints.
What it assumes
Assumes Java and RestTemplate familiarity while explaining OAuth 2 authentication, authorized clients, and request-scoped access to security context.
What you can do after
Build it from scratch by registering a ClientHttpRequestInterceptor that adds a bearer token and delegates request execution.
How it connects
Connects RestTemplate, OAuth 2 client, access tokens, Authorization headers, SecurityContext, and request scope.

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.