In an earlier article, I talked about how to make HTTP requests to consume RESTful web services by using the Spring Framework RestTemplate class.

In this short article, you will learn how to add basic authentication to the requests made by RestTemplate in a Spring Boot application.

In basic HTTP authentication, the outgoing HTTP request contains an authorization header in the following form:

Authorization: Basic <credentials>

Where credentials is a base64 encoded string that is created by combing both user name and password with a colon (:).

There are multiple ways to add this authorization HTTP header to a RestTemplate request.

Add Basic Authentication to a Single Request

The simplest way to add basic authentication to a request is to create an instance of HttpHeaders, set the Authorization header value, and then pass it to the RestTemplate. Here is an example:

try {
    // request url
    String url = "https://jsonplaceholder.typicode.com/posts";

    // create auth credentials
    String authStr = "username:password";
    String base64Creds = Base64.getEncoder().encodeToString(authStr.getBytes());

    // create headers
    HttpHeaders headers = new HttpHeaders();
    headers.add("Authorization", "Basic " + base64Creds);

    // create request
    HttpEntity request = new HttpEntity(headers);

    // make a request
    ResponseEntity<String> response = new RestTemplate().exchange(url, HttpMethod.GET, request, String.class);

    // get JSON response
    String json = response.getBody();

} catch (Exception ex) {
    ex.printStackTrace();
}

In the latest version of Spring Framework (5.1 and higher), you don't need to manually set the authorization header. You can use the setBasicAuth() method from HttpHeaders to pass the login credentials:

// create headers
HttpHeaders headers = new HttpHeaders();
headers.setBasicAuth("username", "password");

The setBasicAuth() method will automatically create the base64 encoded string and set the authorization header.

Add Basic Authentication to All Requests

Sometimes you want to add basic HTTP authentication to all requests to consume secure RESTful web services. It is not good approach to manually set the authorization header for each request.

Fortunately, Spring Boot provides the RestTemplateBuilder class to configure and create an instance of RestTemplate. It includes several convenience methods that can be used to create a customized RestTemplate instance.

To use the RestTemplateBuilder, simply inject it to the class where you want to use the RestTemplate HTTP client:

@Service
public class RestService {

    private final RestTemplate restTemplate;

    public RestService(RestTemplateBuilder restTemplateBuilder) {
        this.restTemplate = restTemplateBuilder
                .basicAuthentication("username", "password")
                .build();
    }
}

Now, the basic authentication will be added to all requests sent through the above restTemaplate instance. You do not need to set the authorization header.

Instead of autowiring the RestTemplateBuilder, you can set the following bean in your Spring Boot main application class:

@Bean
RestOperations restTemplateBuilder(RestTemplateBuilder restTemplateBuilder) {
    return restTemplateBuilder.basicAuthentication("username", "password").build();
}

It will make sure that basic authentication is added to each and every request that is sent by the RestTemplate HTTP client. This solution is not recommended if you call different APIs, as it would add an authorization header to unwanted requests.

Read Next: Spring Boot RestTemplate Error Handling

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.