Spring RestTemplate - Расширение BasicAuthorizationInterceptor - PullRequest
0 голосов
/ 21 декабря 2018

Я пытаюсь реализовать решение с использованием Spring * RestTemplate, которое будет использовать базовую авторизацию и устанавливать определенные заголовки для каждого запроса.Я считаю, что я очень близок к тому, чтобы работать с расширением BasicAuthorizationInterceptor, но у меня проблема с передачей учетных данных к запросу.

Вот мой пользовательский перехватчик запросов, который расширяет BasicAuthorizationInterceptor:

public class CustomRequestInterceptor extends BasicAuthorizationInterceptor {

    public CustomRequestInterceptor(final String username, final String password) {
        super(username, password);
    }

    @Override
    public ClientHttpResponse intercept(final HttpRequest request, final byte[] body,
            final ClientHttpRequestExecution execution) throws IOException {

        final HttpHeaders headers = request.getHeaders();
        headers.setAccept(Collections.singletonList(APPLICATION_PDF));

        return execution.execute(request, body);
    }

}

и вот моя фактическая конфигурация шаблона:

@Configuration
@EnableConfigurationProperties(ServiceProperties.class)
public class CustomRestConfiguration {

    @Autowired
    public ServiceProperties serviceRestProperties;

    @MyApplication
    @Scope(value = CustomScope.NAME, proxyMode = ScopedProxyMode.TARGET_CLASS)
    @Bean
    public RestTemplate customRestTemplate() {
        final RestTemplate restTemplate = new RestTemplate(new CustomClientHttpRequestFactory(
                this.serviceRestProperties.getBaseUrl()));

        restTemplate.getInterceptors().add(
                new CustomRequestInterceptor(this.serviceRestProperties.getUsername(),
                        this.serviceRestProperties.getPassword()));

        return restTemplate;
    }
}

и, наконец, моя фабрика:

public class CustomClientHttpRequestFactory extends HttpComponentsClientHttpRequestFactory {

    private final URI baseUrl;

    public CustomClientHttpRequestFactory(final URI baseUrl) {
        super();
        this.baseUrl = baseUrl;
    }

    @Override
    protected HttpContext createHttpContext(final HttpMethod httpMethod, final URI uri) {

        final AuthCache authCache = new BasicAuthCache();
        final BasicScheme basicScheme = new BasicScheme();
        final BasicHttpContext basicHttpContext = new BasicHttpContext();
        final HttpHost host = new HttpHost(this.baseUrl.getHost(), this.baseUrl.getPort(), this.baseUrl.getScheme());

        authCache.put(host, basicScheme);
        basicHttpContext.setAttribute(AUTH_CACHE, authCache);

        return basicHttpContext;
    }

}

В моем приложении я на самом деле звонюкак это:

final ResponseEntity<Resource> resource = this.restTemplate.getForEntity(uri, Resource.class);

С настройкой выше заголовок принятия установлен правильно, и я вижу это в журналах.Однако Basic Authorization на самом деле не приходит на запрос.Я вижу, что имя пользователя / пароль устанавливаются для объекта в Eclipse.

Теперь , если Я изменяю свою конфигурацию покоя на , неявно , добавляю BasicAuthorizationInterceptor (хотя я не должен был этого делать), тогда это работает.Вот пример добавления обоих перехватчиков:

    @MyApplication
    @Scope(value = CustomScope.NAME, proxyMode = ScopedProxyMode.TARGET_CLASS)
    @Bean
    public RestTemplate customRestTemplate() {
        final RestTemplate restTemplate = new RestTemplate(new CustomClientHttpRequestFactory(
                this.serviceRestProperties.getBaseUrl()));

        restTemplate.getInterceptors().add(
                new CustomRequestInterceptor(this.serviceRestProperties.getUsername(),
                        this.serviceRestProperties.getPassword()));

        restTemplate.getInterceptors().add(
                new BasicAuthorizationInterceptor(this.serviceRestProperties.getUsername(),
                        this.serviceRestProperties.getPassword()));

        return restTemplate;
    }

Как я могу фактически расширить BasicAuthorizationInterceptor, как я намереваюсь, и позволить базовой авторизации проходить через запрос и забратьмои заголовки?

Большое спасибо


Примечание. Мне известно, что BasicAuthorizationInterceptor устарело, но я не могу выполнить обновление до версии 5.1.1.для использования BasicAuthenticationInterceptor только пока;Я сейчас на 5.0.9.

...