com.payu.auth.client.configuration.security.OAuth2RestClientConfig Maven / Gradle / Ivy
package com.payu.auth.client.configuration.security;
import com.payu.common.client.handler.IntermoduleRestTemplateResponseErrorHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.server.resource.authentication.JwtAuthenticationToken;
import org.springframework.web.client.RestTemplate;
/**
* Exposes a {@link RestTemplate} bean that adds an authentication header for the current OAuth2
* client context.
*/
@Configuration
@Slf4j
public class OAuth2RestClientConfig {
@Bean
public RestTemplateBuilder restTemplateBuilder() {
return new RestTemplateBuilder();
}
@Bean
public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
return restTemplateBuilder
.errorHandler(new IntermoduleRestTemplateResponseErrorHandler())
.additionalInterceptors(
(httpRequest, bytes, clientHttpRequestExecution) -> {
if (SecurityContextHolder.getContext().getAuthentication()
instanceof JwtAuthenticationToken token) {
String tokenType = "Bearer";
final String authHeader =
String.format("%s %s", tokenType, token.getToken().getTokenValue());
log.debug("Intercepting HTTP request and adding OAuth2 authentication header");
httpRequest.getHeaders().add(HttpHeaders.AUTHORIZATION, authHeader);
}
return clientHttpRequestExecution.execute(httpRequest, bytes);
})
.build();
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy