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
