Skip to main content

Posts

Showing posts with the label Spring Framework

Spring RestTemplate - How to skip SSL certificates validation?

In this tutorial, we will explore to consume restful web services hosted on https URL with SSL certificates. We will use Sprint RestTemplate to consume the restful web services. It is very easy to consume the web services hosted on HTTP protocol. Challange is consuming the web services hosted on HTTPS with SSL certificates enabled. I encountered the following exception when accessing SSL hosted web services Caused by: javax.net.ssl.SSLHandshakeException:        sun.security.validator.ValidatorException: PKIX path building failed: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target  at sun.security.ssl.Alerts.getSSLException(Alerts.java:192) at sun.security.ssl.SSLSocketImpl.fatal(SSLSocketImpl.java:1917) We will use  SSLContext to skip SSL validation. What is SSL Context? SSL Context is a collection of ciphers, trusted certificates, TLS extensions and options, and protocol versions. It acts as a factory

A complete guide to securing Spring RESTful web services using HTTP Basic Authentication header

In the following tutorial, I have shown you how to develop RESTful web services using Spring Boot Spring Data Rest web services for Beginners - Step By Step Guide This is a simple and easy written tutorial for beginners who are interested to explore the trending and widely used J2EE framework. In this tutorial, we will learn how to secure the Restful web services using the HTTP Basic Authentication header. According to rfc7617,  basic authentication is the method for HTTP user agent to provide the following two pieces of information in a request User Name Password In this method, the HTTP request contains the header in the following format Authorization: Basic <credentials>  where <credentials> is base64(username:password) Step 1 Add the following dependency to the maven <dependency>   <groupId>org.springframework.boot</groupId>   <artifactId>spring-boot-starter-security</artifactId> <dependency> Step

Spring Data Rest web services for beginners - Step By Step Guide

This tutorial is designed for those who have not worked with the Spring Framework or rest web services before. I am keeping it simple and less verbose so that readers can easily follow the steps and start developing the restful web services using Spring Data Rest. Spring Framework is the trending and widely used J2EE frameworks. It has various modules for web development. In this tutorial, we will use the Spring Data Rest. RESTful Web services Representational State Transfer (REST)  is based on server-client architecture and uses the HTTP protocol(stateless protocol). CRUD operations can be easily mapped on HTTP methods Create POST Read GET Update PUT Delete Delete Prerequisites for this tutorial Java 8 or later version Eclipse Maven Let's start developing the RESTful web services STEP 1 Open a new Maven Project in the eclipse, let's call it MyFirstRestApp.  We will use the Spring Boot for this tutorial. Open the maven.xml file and ad

How to change base URI in Spring Data Rest?

If you have worked with Spring Data Rest, you would have observed that by default, Spring serves the requests to the root URI '/'. If you want to append a specific string to the base path, you can specify the following property in application.properties file inside the resources folder spring.data.rest.basePath=/api This solution is provided in Spring Boot 1.2 and later versions. In my case it did not work for me, after searching for it over the internet, I have found the solution,  instead of basePath property, set the following property in application.properties file server.servlet.context-path=/api Please leave your comments.

Spring Boot RestTemplate - Log the Request and Response

Recently when working on a rest client using the Spring's RestTemplate, I needed to log the request and response as I had no clue what was wrong with my code. Spring provides the option to write your own Interceptors. For this specific requirement, Spring provides the  ClientHttpRequestInterceptor interface. I had to override its intercept method and implement my logic there. Below is the snapshot of my code public class MyInterceptor implements ClientHttpRequestInterceptor  {       @Override     public ClientHttpResponse intercept(HttpRequest httpRequest, byte[] body, ClientHttpRequestExecution execution)                 throws IOException {              printRequest(httpRequest, body);             ClientHttpResponse response = execution.execute(httpRequest, body);             printResponse(response);             return response;     }     private void printRequest(HttpRequest httpRequest, byte[] body) throws IOException {                          System.out.print

Spring Rest web services that accepts Generic JSON instead of specific

Recently when working on restful webservices, I came across a situation where I have to receive variant  JSON  in my Request and have to return the variant JSON in response. In previous projects, I was using the specific Java Objects in my request and response.  In the current project, I had no idea how to handle the generic JSON instead of specific Java objects (jackson lib that automatically marshal/unmarshal JSON/Java Objects).  I came across the jackson's JsonNode class. Using JsonNode, I can accept any kind of Json in my request and similarly can return generic Json in my response.

How to avoid HttpStatusCodeException using Spring RestTemplate

I have written a Rest client using the Spring's RestTemplate with the following code  try {               response = restTemplate.exchange( url,HttpMethod.POST, entity , JsonNode.class);  }catch (HttpStatusCodeException codeException) {         String responseBody = codeException.getResponseBodyAsString();            ......................  } catch(Exception ex) {                   ex.printStackTrace();            ObjectMapper mapper = new ObjectMapper();           JsonNode node = mapper.readTree(" { \"error\" : \"" + ex.getMessage() + "\" }" );            response = new ResponseEntity<>(node, HttpStatus.INTERNAL_SERVER_ERROR );  } In the above code, I am not able to read the response body. This is the issue with the RestTemplate default error handler. In order to fix this issue, I have the following two options a) Write my own Error Handler that implements ResponseErrorHandler b) Write my own Error Handler tha