在RestTemplate中,我配置了两个ClientHttpRequestInterceptor(一个用于BasicAuthorization,另一个用于基于令牌的身份验证。
在客户端,我如何要求RestTemplate使用正确的ClientHttpRequestInterceptor来执行API调用。
某些API调用需要BasicAuthorization才能起作用。 (例如:如果URL以“ / admin”开头,则需要BasicAuthorization,其他则需要基于令牌的身份验证)
我如何在Spring 4中实现这一目标?
答案 0 :(得分:1)
您可以使用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;
}