Вы можете использовать два экземпляра RestTemplate, один для базовой аутентификации и один для аутентификации токена.
@Bean
@Qualifier("authRestTemplate")
public RestTemplate getAuthTemplate{
// create rest template, add auth interceptor
}
@Bean
@Qualifier("tokenRestTemplate")
public RestTemplate getTokenTemplate{
// create rest template, add token interceptor
}
Затем, при автоматическом подключении RestTemplate, используйте нужный @ Qualifier
@Autowired
@Qualifier("authRestTemplate")
private RestTemplate authTemplate;
@Autowired
@Qualifier("tokenRestTemplate")
private RestTemplate tokenTemplate;
Другим вариантом будет добавление двух ClientHttpRequestInterceptor
к RestTemplate
class BasicAuthInterceptor implements ClientHttpRequestInterceptor {
private final AuthService authService;
public BasicAuthHeaderInterceptor(AuthService authService) {
this.authService = authService;
}
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
if(isApplicable(request)){
String token = Base64Utils.encodeToString((authService.getUsername() + ":" + authService.getpassword()).getBytes(Charset.forName("UTF-8")));
request.getHeaders().add("Authorization", "Basic " + token);
}
return execution.execute(request, body);
}
}
class TokenInterceptor implements ClientHttpRequestInterceptor {
private final AuthService authService;
public TokenHeaderInterceptor(AuthService authService) {
this.authService = authService;
}
@Override
public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
if(isApplicable(request)){
request.getHeaders().add("Authorization", "Bearer " + tokenService.getToken());
}
return execution.execute(request, body);
}
}
Затем добавьте два перехватчика к RestTemplate
@Bean
public RestTemplate restTemplate(){
RestTemplate template = new RestTemplate();
template.getInterceptors().add(new BasicAuthInterceptor(authService));
template.getInterceptors().add(new TokenInterceptor(authService));
return template;
}