Как работать с несколькими ClientHttpRequestInterceptors в Spring 4 - PullRequest
0 голосов
/ 18 сентября 2018

В RestTemplate я настроил два ClientHttpRequestInterceptor (один для BasicAuthorization и другой для аутентификации на основе токенов.

Со стороны клиента, как я запрашиваю RestTemplate для использования правильного ClientHttpRequestInterceptor для выполнения вызова API.

Для некоторых вызовов API требуется BasicAuthorization. (Например, если URL начинается с "/ admin", требуется BasicAuthorization, для других требуется аутентификация на основе токена)

Как я могу добиться этого в Spring 4?

1 Ответ

0 голосов
/ 18 сентября 2018

Вы можете использовать два экземпляра 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;
}
...