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
