RestTemplate with Basic Authentication

Carvia Tech | December 30, 2019 | 3 min read | 107 views


We will configure RestTemplate in Spring Boot application to use basic authentication credentials in order to access protected resources on remote server.

Perquisites

  1. Gradle 6

  2. Java 8 or 11

  3. Spring Boot and RestTemplate

  4. Junit 5

  5. IDE - IntelliJ IDEA or Eclipse

Download Basic Auth Server

Creating the basic auth server is outside the scope for this tutorial, you can just clone this project and run it from command line.

Starting the Server

$ ./gradlew :bootRun

Now we should have the following endpoint running on the server - http://localhost:8080/secured/hello

Gradle Setup

We will setup Spring Boot dependencies in build.gradle

build.gradle
plugins {
    id 'org.springframework.boot' version '2.2.2.RELEASE'
    id 'java'
}

apply plugin: 'io.spring.dependency-management'

group = 'com.shunya.tutorial'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'

repositories {
    mavenCentral()
}

dependencies {
    implementation 'org.springframework.boot:spring-boot-starter-web'
}

We have roughly 3 different approaches to tackle basic authentication:

  1. Creating a customized RestTemplate using RestTemplateBuilder (preferred approach for Spring Boot)

  2. Using RestTemplate Interceptors

  3. Using Headers on each request level

1. RestTemplate customization with RestTemplateBuilder

We will be using RestTemplateBuilder to create a customized version of RestTemplate that attaches Basic Authentication headers with each outgoing request.

RestTemplate with Basic Authentication
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

@Component
public class BasicAuthClient {

    private final RestTemplate restTemplate;

    public BasicAuthClient(RestTemplateBuilder restTemplateBuilder) {
        restTemplate = restTemplateBuilder
                    .basicAuthentication("admin", "password")
                    .build();
    }

    public void invokeProtectedResource() {
        final ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://localhost:8080/secured/hello", String.class);
        final String body = responseEntity.getBody();
        System.out.println("body = " + body);
    }
}

2. Using RestTemplate Interceptors

We can configure interceptor at RestTemplate instance level that will inject required basic auth headers on each outgoing request.

BasicAuthClient.java
public class BasicAuthClient {

    private final RestTemplate restTemplate;

    public BasicAuthClient(RestTemplateBuilder restTemplateBuilder) {
        restTemplate = restTemplateBuilder.build();
        restTemplate.getInterceptors().add(new BasicAuthenticationInterceptor("admin", "password"));
    }

    private void invokeProtectedResource() {
        final ResponseEntity<String> responseEntity = restTemplate.getForEntity("http://localhost:8080/secured/hello", String.class);
        final String body = responseEntity.getBody();
        System.out.println("body = " + body);
    }
}

BasicAuthenticationInterceptor is provided by Spring Framework. You can also provide your own Interceptor definition.

Custom Interceptor for RestTemplate
restTemplate.getInterceptors().add(new ClientHttpRequestInterceptor() {
    @Override
    public ClientHttpResponse intercept(HttpRequest request, byte[] body, ClientHttpRequestExecution execution) throws IOException {
        String auth = "admin" + ":" + "password";
        byte[] encodedAuth = Base64.encodeBase64(auth.getBytes(StandardCharsets.US_ASCII));
        request.getHeaders().add("Authorization", "Basic " + new String(encodedAuth));
        return execution.execute(request, body);
    }
});

3. Request level headers

Instead of setting basic auth at instance level, we can also set it at individual request level using the following code:

RestTemplate request level headers for basic auth
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.nio.charset.StandardCharsets;

@Component
public class BasicAuthClient {

    private final RestTemplate restTemplate;

    public BasicAuthClient(RestTemplateBuilder restTemplateBuilder) {
        restTemplate = restTemplateBuilder.build();
    }

    HttpHeaders createHeaders(String username, String password) {
        return new HttpHeaders() {{
            final String basicAuth = HttpHeaders.encodeBasicAuth(username, password, StandardCharsets.US_ASCII);
            setBasicAuth(basicAuth);
        }};
    }

    private void invokeProtectedResource() {
        final ResponseEntity<String> responseEntity = restTemplate.exchange("http://localhost:8080/secured/hello", HttpMethod.GET, new HttpEntity<Void>(createHeaders("admin", "password")), String.class);
        System.out.println(responseEntity.getBody());
    }
}

Top articles in this category:
  1. Basic Auth Security in Spring Boot 2
  2. Disable SSL certificate validation in RestTemplate
  3. File Upload in Spring MVC using RestTemplate with ByteArrayResource & FileSystemResource
  4. Send Gupshup SMS using Java API
  5. What is difference between Component, Repository, Service, Controller & RestController
  6. Invoking AWS Lambda from a Java Client
  7. SendGrid emails with Spring Boot and Java


Find more on this topic:
Spring Framework image
Spring Framework

Spring Framework - MVC, Dependency Injection, Spring Hibernate, Spring Data JPA, Spring Boot and Spring Cloud for Microservices Architecture.

Last updated 1 week ago


Recommended books for interview preparation:

This website uses cookies to ensure you get the best experience on our website. more info