Skip to content

DiKode

Coding Journal

Menu
  • Home
  • Author
  • Contact Me
  • Category
    • Java
    • Javascript
  • Privacy Policy
Menu

How to Configure Basic Auth Spring RestTemplate

Posted on April 13, 2017October 26, 2017 by didikhari

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.


[java]
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 headers = new LinkedMultiValueMap();

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 sendRequest(String targetUrl, MultiValueMap requestObject,
Class responseType, HttpMethod method){

HttpEntity request = new HttpEntity(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 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;
}
}
[/java]

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.

[xml]




[/xml]

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

Leave a Reply Cancel reply

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

Categories

  • Java
  • Javascript
  • jPOS

Recent Post

  • jPOS Server in-out
  • How to Configure Basic Auth Spring RestTemplate
  • Create Custom jPOS ISO8583 Packager
  • Binding Restful XML Parameter
  • Create Dynamic Tree Grid using TreeGrid jQuery Plugin

Tags

Asynchronous Request async request Bind Json Param custom channel custom jPOS packager datatables Design Pattern hibernate http http basic auth http request iso 8583 java javascript jPOS jpos channel jPOS Client jPOS database jPOS deploy directory jPOS Hibernate jpos http jpos rest jPOS Server jpos Space jquery js jsf load balancer moxy mux mux pool prettyfaces primefaces rest client Restful SAF space Specifications spring framework TCP Template Method transaction manager transaction participant tree TreeGrid

Meta

  • Log in
  • Entries feed
  • Comments feed
  • WordPress.org
©2021 DiKode | Built using WordPress and Responsive Blogily theme by Superb