【问题标题】:Spring Framework 3.2 : How to add basic authentication for all Requests through RestTemplateSpring Framework 3.2:如何通过 RestTemplate 为所有请求添加基本身份验证
【发布时间】:2020-06-24 12:42:46
【问题描述】:

我正在开发一个 Spring 框架 3.2 版本的项目。要求是调用需要基本身份验证的外部 Web 服务。

目前,我正在使用 HttpClient 并将基本身份验证添加到标头中。但这是针对每个请求进行的。我知道在 Spring Boot 中我们可以通过使用 RestTemplateBuilder 来实现。有没有一种方法可以通过只添加一次身份验证来为所有请求维护一个单一的身份验证?

TIA

【问题讨论】:

    标签: spring spring-mvc basic-authentication resttemplate


    【解决方案1】:

    您可以定义一个RestTemplate bean,其身份验证详细信息如下:

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        return builder.basicAuthorization("user", "secret").build();
    }
    

    更新

    另一种方法是实现拦截器。 RestTemplate 扩展了具有setInterceptors() 方法的InterceptingHttpAccessor 接口。您可以使用它来注入拦截器以根据需要设置请求标头。

    public class MyInterceptor implements ClientHttpRequestInterceptor {
     
        @Override
        public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
            // ... set headers on the request ...
            return execution.execute(request, body);
        }
    }
    
    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
        RestTemplate restTemplate = new RestTemplate();
        restTemplate.setInterceptors(Collections.singletonList(new MyInterceptor()))
        return restTemplate
    }
    

    注意:未经测试的代码,但应该可以工作。您可以查看文档以获取更多详细信息。

    https://docs.spring.io/autorepo/docs/spring-framework/3.2.0.RELEASE/javadoc-api/index.html?org/springframework/web/client/RestTemplate.html

    【讨论】:

    • RestTemplateBuilder 不是 Spring 框架 3.2 的一部分。我已经在问题中指定了这一点。你能提供一个spring framework 3.2的解决方案吗?
    • 我的错误。添加了替代解决方案。
    【解决方案2】:

    HttpClient 可以从HttpClientBuilder 构建。

    这个构建器有setDefaultHeaders(Collection<? extends org.apache.http.Header> defaultHeaders) 方法,你可以设置你想要的标题。然后,当您需要 HttpClient 时,请致电 httpClientBuilder.build()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-19
      • 2017-12-22
      • 1970-01-01
      • 2017-01-02
      • 2014-03-26
      • 1970-01-01
      • 2018-07-30
      • 2018-01-22
      相关资源
      最近更新 更多