The Apache HTTP Client is a very robust library, suitable for both simple and advanced use cases when testing HTTP endpoints. Check out our guide covering basic request and response handling, as well as security, cookies, timeouts, and more:
Mocking is an essential part of unit testing, and the Mockito library makes it easy to write clean and intuitive unit tests for your Java code.
Get started with mocking and improve your application tests using our Mockito guide:
Handling concurrency in an application can be a tricky process with many potential pitfalls. A solid grasp of the fundamentals will go a long way to help minimize these issues.
Get started with understanding multi-threaded applications with our Java Concurrency guide:
Spring 5 added support for reactive programming with the Spring WebFlux module, which has been improved upon ever since. Get started with the Reactor project basics and reactive programming in Spring Boot:
Since its introduction in Java 8, the Stream API has become a staple of Java development. The basic operations like iterating, filtering, mapping sequences of elements are deceptively simple to use.
But these can also be overused and fall into some common pitfalls.
To get a better understanding on how Streams work and how to combine them with other language features, check out our guide to Java Streams:
Get started with Spring and Spring Boot, through the Learn Spring course:
>> LEARN SPRINGExplore Spring Boot 3 and Spring 6 in-depth through building a full REST API with the framework:
Yes, Spring Security can be complex, from the more advanced functionality within the Core to the deep OAuth support in the framework.
I built the security material as two full courses - Core and OAuth, to get practical with these more complex scenarios. We explore when and how to use each feature and code through it on the backing project.
You can explore the course here:
Spring Data JPA is a great way to handle the complexity of JPA with the powerful simplicity of Spring Boot.
Get started with Spring Data JPA through the guided reference course:
Refactor Java code safely β and automatically β with OpenRewrite.
Refactoring big codebases by hand is slow, risky, and easy to put off. Thatβs where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.
Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions β one for newcomers and one for experienced users. Youβll see how recipes work, how to apply them across projects, and how to modernize code with confidence.
Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.
Table of Contents
- 1. Overview
- 2. Setting up the RestTemplate in Spring
- 3. Manual management of the Authorization HTTP header
- 4. Automatic management of the Authorization HTTP header
- 5. Maven dependencies
- 6. Conclusion
1. Overview
In this tutorial, weβll learn how to use Springβs RestTemplate to consume a RESTful Service secured with Basic Authentication.
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: Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==
Further reading:
Spring RestTemplate Error Handling
Using the Spring RestTemplate Interceptor
Exploring the Spring Boot TestRestTemplate
2. Setting up the 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:
@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.
3. Manual Management of the Authorization HTTP Header
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:
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
Spring 3.0 and 3.1, and now 4.x, have very good support for the Apache HTTP libraries:
- 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.
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:
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.
Now that everything is in place, the RestTemplate will be able to support the Basic Authentication scheme just by adding a 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.
5. Maven Dependencies
Weβll require the following Maven dependencies for the RestTemplate itself and for the HttpClient library:
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>6.0.13</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents.client5</groupId>
<artifactId>httpclient5</artifactId>
<version>5.2.1</version>
</dependency>
Optionally, if we construct the HTTP Authorization header manually, then weβll require an additional library for the encoding support:
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
We can find the newest versions in the Maven repository: spring-webmvc, httpclient5 and commons-codec.
6. Conclusion
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.
This is a Maven-based project, so it should be easy to import and run as is.
