# How to use basic authentication with RestTemplate

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published Sep 21, 2019, updated Sep 24, 2022. Topics: Spring Boot.
Canonical URL: https://attacomsian.com/blog/resttemplate-basic-authentication

> A quick guide to learning how to add basic Authentication to the requests made by RestTemplate in a Spring Boot application.

In an [earlier article](https://attacomsian.com/blog/http-requests-resttemplate-spring-boot), 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:

```http
Authorization: Basic <credentials>
```

Where `credentials` is a [base64 encoded string](https://attacomsian.com/blog/base64-encode-decode-java) 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:

```java
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:

```java
// 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:

```java
@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:

```java
@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](https://attacomsian.com/blog/spring-boot-resttemplate-error-handling)
