Basic Authentication with the RestTemplate – 用RestTemplate进行基本认证

最后修改: 2014年 2月 23日

中文/混合/英文(键盘快捷键:t)

Table of Contents

目录

1. Overview

1.概述

In this tutorial, we’ll learn how to use Spring’s RestTemplate to consume a RESTful Service secured with Basic Authentication.

在本教程中,我们将学习如何使用Spring的RestTemplate消费一个有基本认证的RESTful服务

Once we set up Basic Authentication for the template, each request will be sent preemptively containing the full credentials necessary to perform the authentication process. The credentials will be encoded, and use the Authorization HTTP Header, in accordance with the specs of the Basic Authentication scheme. An example would look like this:

一旦我们为模板设置了基本认证,每个请求将被发送先发制人地包含执行认证过程所需的全部凭证。凭证将被编码,并根据基本认证方案的规格使用Authorization HTTP Header。一个例子是这样的。

Authorization: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==

2. Setting up the RestTemplate

2.设置RestTemplate

We can bootstrap the RestTemplate into the Spring context simply by declaring a bean for it; however, setting up the RestTemplate with Basic Authentication will require manual intervention, so instead of declaring the bean directly, we’ll use a Spring FactoryBean for more flexibility. This FactoryBean will create and configure the template on initialization:

我们可以通过为其声明一个Bean来将RestTemplate引导到Spring上下文中;然而,用Basic Authentication来设置RestTemplate将需要人工干预,因此我们将使用Spring的FactoryBean来代替直接声明Bean,以提高灵活性。这个FactoryBean将在初始化时创建和配置该模板。

@Component
public class RestTemplateFactory
  implements FactoryBean<RestTemplate>, InitializingBean {
 
    private RestTemplate restTemplate;

    public RestTemplate getObject() {
        return restTemplate;
    }
    public Class<RestTemplate> getObjectType() {
        return RestTemplate.class;
    }
    public boolean isSingleton() {
        return true;
    }

    public void afterPropertiesSet() {
        HttpHost host = new HttpHost("localhost", 8082, "http");
        restTemplate = new RestTemplate(
          new HttpComponentsClientHttpRequestFactoryBasicAuth(host));
    }
}

The host and port values should be dependent on the environment, allowing the client the flexibility to define one set of values for integration testing and another for production use. The values can be managed by the first class Spring support for properties files.

hostport值应取决于环境,允许客户灵活地定义一组用于集成测试的值和另一组用于生产使用的值。这些值可以由第一类Spring对属性文件的支持来管理。

3. Manual Management of the Authorization HTTP Header

3.授权HTTP头的手动管理

It’s fairly straightforward for us to create the Authorization header for Basic Authentication, so we can do it manually with a few lines of code:

对我们来说,为基本认证创建Authorization头是相当直接的,所以我们可以用几行代码手动完成。

HttpHeaders createHeaders(String username, String password){
   return new HttpHeaders() {{
         String auth = username + ":" + password;
         byte[] encodedAuth = Base64.encodeBase64( 
            auth.getBytes(Charset.forName("US-ASCII")) );
         String authHeader = "Basic " + new String( encodedAuth );
         set( "Authorization", authHeader );
      }};
}

Furthermore, sending a request is just as simple:

此外,发送请求也同样简单。

restTemplate.exchange
 (uri, HttpMethod.POST, new HttpEntity<T>(createHeaders(username, password)), clazz);

4. Automatic Management of the Authorization HTTP Header

4.授权HTTP头的自动管理

Spring 3.0 and 3.1, and now 4.x, have very good support for the Apache HTTP libraries:

Spring 3.0和3.1,以及现在的4.x,对Apache HTTP库有很好的支持。

  • In Spring 3.0, the CommonsClientHttpRequestFactory integrated with the now end-of-life’d HttpClient 3.x.
  • Spring 3.1 introduced support for the current HttpClient 4.x via HttpComponentsClientHttpRequestFactory (support added in the JIRA SPR-6180).
  • Spring 4.0 introduced async support via the HttpComponentsAsyncClientHttpRequestFactory.

Let’s start setting things up with HttpClient 4 and Spring 4.

让我们开始用HttpClient 4和Spring 4设置东西。

The RestTemplate will require an HTTP request factory that supports Basic Authentication. However, using the existing HttpComponentsClientHttpRequestFactory directly will prove to be difficult, as the architecture of RestTemplate was designed without good support for HttpContext, an instrumental piece of the puzzle. As such, we’ll need to subclass HttpComponentsClientHttpRequestFactory and override the createHttpContext method:

RestTemplate将需要一个支持基本认证的HTTP请求工厂。然而,直接使用现有的HttpComponentsClientHttpRequestFactory将被证明是困难的,因为RestTemplate的架构被设计为没有对HttpContext的良好支持,这是难题中重要的一部分。因此,我们需要对HttpComponentsClientHttpRequestFactory进行子类化并覆盖createHttpContext方法。

public class HttpComponentsClientHttpRequestFactoryBasicAuth 
  extends HttpComponentsClientHttpRequestFactory {

    HttpHost host;

    public HttpComponentsClientHttpRequestFactoryBasicAuth(HttpHost host) {
        super();
        this.host = host;
    }

    protected HttpContext createHttpContext(HttpMethod httpMethod, URI uri) {
        return createHttpContext();
    }
    
    private HttpContext createHttpContext() {
        AuthCache authCache = new BasicAuthCache();

        BasicScheme basicAuth = new BasicScheme();
        authCache.put(host, basicAuth);

        BasicHttpContext localcontext = new BasicHttpContext();
        localcontext.setAttribute(HttpClientContext.AUTH_CACHE, authCache);
        return localcontext;
    }
}

We built the basic authentication support in here, in the creation of the HttpContext. As we can see, it’s a bit of a burden for us to do preemptive Basic Authentication with HttpClient 4.x. The authentication info is cached, and it’s very manual and non-intuitive for us to set up this authentication cache.

我们在创建HttpContext的时候,在这里建立了基本认证支持。正如我们所看到的,用HttpClient 4.x做抢先的基本认证对我们来说是一个负担。认证信息是被缓存的,对我们来说,设置这个认证缓存是非常手动和非直观的。

Now that everything is in place, the RestTemplate will be able to support the Basic Authentication scheme just by adding a BasicAuthorizationInterceptor:

现在一切就绪,RestTemplate将能够支持基本认证方案,只需添加一个BasicAuthorizationInterceptor:即可。

restTemplate.getInterceptors().add(
  new BasicAuthorizationInterceptor("username", "password"));

Then the request:

然后是请求。

restTemplate.exchange(
  "http://localhost:8082/spring-security-rest-basic-auth/api/foos/1", 
  HttpMethod.GET, null, Foo.class);

For an in-depth discussion on how to secure the REST Service itself, check out this article.

关于如何确保REST服务本身安全的深入讨论,查看此文章

5. Maven Dependencies

5.Maven的依赖性

We’ll require the following Maven dependencies for the RestTemplate itself and for the HttpClient library:

我们需要为RestTemplate本身和HttpClient库提供以下Maven依赖项。

<dependency>
   <groupId>org.springframework</groupId>
   <artifactId>spring-webmvc</artifactId>
   <version>5.0.6.RELEASE</version>
</dependency>

<dependency>
   <groupId>org.apache.httpcomponents</groupId>
   <artifactId>httpclient</artifactId>
   <version>4.5.3</version>
</dependency>

Optionally, if we construct the HTTP Authorization header manually, then we’ll require an additional library for the encoding support:

另外,如果我们手动构建HTTP Authorization头,那么我们就需要一个额外的库来支持编码。

<dependency>
   <groupId>commons-codec</groupId>
   <artifactId>commons-codec</artifactId>
   <version>1.10</version>
</dependency>

We can find the newest versions in the Maven repository.

我们可以在Maven repository.

6. Conclusion

6.结论

Much of the information that can be found on RestTemplate and security still doesn’t account for the current HttpClient 4.x releases, even though the 3.x branch is end-of-life’d and Spring’s support for that version is fully deprecated. In this article, we attempt to change that by going through a detailed, step by step discussion on how to set up Basic Authentication with the RestTemplate and use it to consume a secured REST API.

许多关于RestTemplate和安全的信息仍然没有考虑到当前的HttpClient 4.x版本,尽管3.x分支已经过期,而且Spring对该版本的支持已经完全失效了。在这篇文章中,我们试图改变这种情况,详细地、一步一步地讨论如何用RestTemplate设置基本认证,并使用它来消费一个安全的REST API。

To go beyond the code samples in this article with the implementation of the consuming side and the actual RESTful Service, have a look at the project over on Github.

要超越本文中的代码示例,实现消费端和实际的RESTful服务,请看Github上的项目

This is a Maven-based project, so it should be easy to import and run as is.

这是一个基于Maven的项目,所以应该很容易导入并按原样运行。