How to Configure Basic Auth Spring RestTemplate

Hi, its been a while since my last post. there are some project that taking more time, so i’m not updating this blog until now, some friends contact me asking about my post, i try my best to reply them. How to Configure Basic Auth Spring RestTemplate.

Today, i will share about How to Configure Basic Auth on Spring RestTemplate.
Spring ResTemplate is very useful class to consuming any rest api, by default its not using any Authentication Method.
The example of Basic Auth is something like this:

Authorization:Basic ZXllc29jY2VyOmV5ZXNvY2NlcjIwMTc=

There are many API Authentication Type you can read How to Secure Your REST API using Proven Best Practices. i think the most popular is using OAuth 2, but the easiest way is using Basic Auth. you can modify this method to use another Auth Type.

Ok, lets down to the code.. First, create BasicRestClient.java that extends Spring’s RestTemplate, and create constructor with username and password parameter. The constructor will create Base64 encoded String used for Authentication header.


package com.didikhari.integration.rest;

import java.net.URI;
import java.net.URISyntaxException;

import org.apache.commons.codec.binary.Base64;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.social.support.URIBuilder;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

public class BasicRestClient extends RestTemplate {
	private final transient Logger logger = LogManager.getLogger(getClass());
	
	private MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
	
	public BasicRestClient(String username, String password) {
		super();
		getMessageConverters().add(new MappingJackson2HttpMessageConverter());
		
		String base64Auth = Base64.encodeBase64String((username+":"+password).getBytes());
		headers.add("Authorization", "Basic " + base64Auth);
	}
	
	public <T> T sendRequest(String targetUrl, MultiValueMap<String, String> requestObject, 
			Class<T> responseType, HttpMethod method){

		HttpEntity<Object> request = new HttpEntity<Object>(requestObject, headers);		
		try {
			URI url = new URI(targetUrl);
			T response = null;
			
			if(method.equals(HttpMethod.POST)){
				logger.info("Sending POST request: "+targetUrl);
				response = postForObject(url, request, responseType);
				
			}else{
				logger.info("Sending GET request: "+targetUrl);
				if(requestObject != null) {
					URIBuilder uri = URIBuilder.fromUri(targetUrl).queryParams(requestObject);
					ResponseEntity<T> exchange = exchange(uri.build(), HttpMethod.GET, request, responseType);
					response = exchange.getBody();
				}
				else{
					response = getForObject(targetUrl, responseType);
				}
			}
			return response;
		} catch (URISyntaxException e) {
			logger.fatal("[ERROR] Failed to Send Request", e);
		}
		return null;
	}
}

And then, we need to declare that class as Spring’s Bean, if you are using xml configuration, you can put this tag to your applicationContext.xml after that, you can Autowire basicRestClient bean to your controller class or service class, or another Spring bean.

<bean id="basicRestClient" class="com.sepakbole.integration.rest.BasicRestClient">
	<constructor-arg index="0" name="username" value="${basic.api.username}" />
	<constructor-arg index="1" name="password" value="${basic.api.password}" />
</bean>

That’s it! its easy as that how to Configure Basic Auth Spring RestTemplate.

Leave a Reply

Your email address will not be published. Required fields are marked *