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), it is no longer required 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 a good approach to manually set the authorization header for each request.

Fortunately, Spring Boot provides RestTemplateBuilder class to configure and create an instance of RestTemplate. It includes a number of 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 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 the basic authentication is added to each and every request that is made by the RestTemplate HTTP client. This solution is not recommended if you are calling different APIs as it would add an authorization header to unwanted requests.

Read Next: Spring Boot RestTemplate Error Handling

✌️ Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV. Buy me a coffee (cost $3)

Need help to start a new Spring Boot or MEAN stack project? I am available for contract work. Hire me to accomplish your business goals with engineering and design. Let’s talk about your project: hi@attacomsian.com.