Using RestTemplate with Basic Auth

Recently I was trying to write integration tests using Spring’s RestTemplate to make REST calls to an integration server. The server was secured using basic auth over https, and the SSL certificate was a self-signed cert created for development use only. I wanted to use RestTemplate to retrieve JSON objects and convert them to POJO’s for asserting values in the test. However it turned out that most of the examples online did not deal with this particular scenario or were out of date. So here is how to use Spring 4’s RestTemplate with the latest Apache HTTPClient (version 4.3.1 as of this writing) over HTTPS.

One complication was that the cert was self-signed. This is easily acceptable if using curl with the “-k” option, but with RestTemplate it requires a little more work to accept the cert.

Spring’s RestTemplate integrates with Apache HttpClient, it’s just the HttpClient that needs to be configured with the username, password, and to accept an insecure cert. Here is the code:

SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, new TrustSelfSignedStrategy()).useTLS().build();
SSLConnectionSocketFactory connectionFactory = new SSLConnectionSocketFactory(sslContext, new AllowAllHostnameVerifier());
BasicCredentialsProvider credentialsProvider = new BasicCredentialsProvider();
credentialsProvider.setCredentials(AuthScope.ANY, new UsernamePasswordCredentials("username", "mypassword"));

HttpClient httpClient = HttpClientBuilder.create()
                                        .setSSLSocketFactory(connectionFactory)
                                        .setDefaultCredentialsProvider(credentialsProvider)
                                        .build();

ClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);

Finally, the request factory is used to construct a new RestTemplate which can make the call to the server.

RestTemplate template = new RestTemplate(requestFactory);
ResponseEntity<User> response = template.postForEntity("https://localhost:8000/path/to/user/1", "", User.class);
User userResponse = response.getBody();

assertEquals(1L, userResponse.getId());

Fortunately the test passes… now we can run integration tests with JUnit at will! Happy Testing!

Advertisements

5 Comments

Filed under Software Engineering

5 responses to “Using RestTemplate with Basic Auth

  1. song

    thanks for your posting.
    It was big help to me. ^^
    -from Korean

  2. Mister G

    Thank you! After hours of searching this was my solution.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s