Today is Monday, 2nd March 2020

Archive for the ‘How-To’ Category


Spring REST API: How to disable HTTP Delete/Put methods

Question

I had a student ask the question:
How can I disable HTTP Options/Delete/Put methods? At the application level it should support only GET and POST requests. Other request methods like put/delete need to be blocked. I am using Spring Boot, Spring MVC and Rest services.

Answer

One possible solution is to make use of Spring Interceptors. Spring Interceptors can intercept HTTP requests for an application and perform pre-processing and post-processing.

For this solution, we will create an interceptor that will pre-process the HTTP requests. If the request does not match our approved HTTP methods then we will reject the requests. In this case, we will only approve HTTP GET and POST requests.

Development Process

Here’s the development process
1. Create a sample REST API
2. Develop a Spring Interceptor
3. Configure the Spring Interceptor for URL mappings

Source Code

All of the solution source code is available for download:
spring-rest-api-block-http-methods.zip

Development

Let’s walk through the development process.

1. Create a sample REST API

For this example, I’ll create a simple REST API

  • GET: /api/demo
  • POST: /api/demo
  • PUT: /api/demo
  • DELETE: /api/demo
  • PATCH: /api/demo

We want to create code that will only allow GET and POST requests to the /api/demo endpoint.

Let’s start by creating a simple REST API. You can use the Spring Initializr website to create a Spring Boot application. For the dependency, be sure to select Spring Web.

Once you have Spring Boot application generated and imported into your IDE, then you can start creating a simple REST API.

Here is the code for our REST API: /api/demo

package com.example.demoapi.controller;

import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/api/demo")
public class DemoController {

    @GetMapping
    public String doGet(HttpServletRequest request) {
        return "in request: "  + request.getMethod();
    }

    @PostMapping
    public String doPost(HttpServletRequest request) {
        return "in request: "  + request.getMethod();
    }

    @PutMapping
    public String doPut(HttpServletRequest request) {
        return "in request: "  + request.getMethod();
    }

    @DeleteMapping
    public String doDelete(HttpServletRequest request) {
        return "in request: "  + request.getMethod();
    }

    @PatchMapping
    public String doPatch(HttpServletRequest request) {
        return "in request: "  + request.getMethod();
    }

}

This code simply create a REST endpoint for /api/demo. It supports the HTTP methods: GET, POST, PUT, DELETE, PATCH and OPTIONS. The methods simply return the HTTP method that is begin processed.

2. Develop a Spring Interceptor

In this section, let’s create an interceptor that will pre-process the HTTP requests. If the request does not match our approved HTTP methods then we will reject the requests. In this case, we will only approve HTTP GET and POST requests.

package com.example.demoapi.interceptor;

import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class DemoInterceptor extends HandlerInterceptorAdapter {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String theMethod = request.getMethod();

        if (HttpMethod.GET.matches(theMethod) || HttpMethod.POST.matches(theMethod)) {
            // GET, POST methods are allowed
            return true;
        }
        else {
            // everything else is not allowed
            response.sendError(HttpStatus.METHOD_NOT_ALLOWED.value());
            return false;
        }
    }
}

As you can see, the code checks the method being processed. If the HTTP method is GET or POST then it returns true. This tells the Spring framework that this interceptor has passed successfully and the request can continue processing.

If the HTTP method is not GET or POST then the interceptor send a a response error code: 405 – Method Not Allowed. The method also returns false which tells the Spring framework to that this interceptor did not pass and the the request should not continue processing further to the API.

3. Configure the Spring Interceptor for URL Mappings

The final step in development is to configure the Spring Interceptor for given URL mappings. Here’s the code:

package com.example.demoapi.config;

import com.example.demoapi.interceptor.DemoInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class DemoConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new DemoInterceptor()).addPathPatterns("/api/demo*/**");
    }
}

This code adds the interceptor to the registry of interceptors. The interceptor is mapped to the path pattern: /api/demo*/**. This will match on any requests for api/demo and also sub-directories. This syntax makes use of wildcards with the Ant patch matcher syntax.

If you want to apply to the entire application, you can use /*.

Unit Testing

Now that the code is created, let’s test it with Spring Boot Unit testing. This collection of tests with access the end point using different HTTP request methods.

package com.example.demoapi;

import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.request.MockMvcRequestBuilders;
import org.springframework.test.web.servlet.result.MockMvcResultMatchers;

@SpringBootTest
@AutoConfigureMockMvc
class DemoapiApplicationTests {

    @Test
    public void getRequestShouldReturn_ok_200(@Autowired MockMvc mockMvc) throws Exception {

        mockMvc.perform(MockMvcRequestBuilders.get("/api/demo"))
				.andExpect(MockMvcResultMatchers.status().isOk());
    }

    @Test
    public void postRequestShouldReturn_ok_200(@Autowired MockMvc mockMvc) throws Exception {

        mockMvc.perform(MockMvcRequestBuilders.post("/api/demo")
				.content("{\"name\": \"demo\"}"))
				.andExpect(MockMvcResultMatchers.status().isOk());
    }

    @Test
    public void putRequestShouldReturn_notallowed_405(@Autowired MockMvc mockMvc) throws Exception {

        mockMvc.perform(MockMvcRequestBuilders.put("/api/demo/1")
				.content("{\"name\": \"demo\"}"))
				.andExpect(MockMvcResultMatchers.status().isMethodNotAllowed());
    }

    @Test
    public void deleteRequestShouldReturn_notallowed_405(@Autowired MockMvc mockMvc) throws Exception {

        mockMvc.perform(MockMvcRequestBuilders.delete("/api/demo/1")
				.content("{\"name\": \"demo\"}"))
 				.andExpect(MockMvcResultMatchers.status().isMethodNotAllowed());
    }

    @Test
    public void patchRequestShouldReturn_notallowed_405(@Autowired MockMvc mockMvc) throws Exception {

        mockMvc.perform(MockMvcRequestBuilders.patch("/api/demo/1")
				.content("{\"name\": \"demo\"}"))
				.andExpect(MockMvcResultMatchers.status().isMethodNotAllowed());
    }

    @Test
    public void optionsRequestShouldReturn_notallowed_405(@Autowired MockMvc mockMvc) throws Exception {

        mockMvc.perform(MockMvcRequestBuilders.options("/api/demo"))
				.andExpect(MockMvcResultMatchers.status().isMethodNotAllowed());
    }

}

For the HTTP methods GET and POST, the application should work successfully and return status code of 200 – Ok.

For the HTTP methods: PUT, DELETE, PATCH and OPTIONS, the application should return 405 – Not Allowed.

You can run the unit test with the following command:

mvn clean test

After running the tests, you should see these test results:

...
...
[INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0 ...
...
 [INFO] 
 [INFO] Results:
 [INFO] 
 [INFO] Tests run: 6, Failures: 0, Errors: 0, Skipped: 0
 [INFO] 
 [INFO] ------------------------------------------------------------------------
 [INFO] BUILD SUCCESS

Run The Application

Now, you can run the application with the command:

mvn spring-boot:run

Test with curl

Now that the application is up and running you can test the application with any REST client testing tool such as Postman etc. In this example, I’ll make use of the curl utility.

Testing GET requests
curl http://localhost:8080/api/demo

The GET request will return successfully.

Testing POST requests
curl -X POST  http://localhost:8080/api/demo

The POST request will return successfully.

Testing PUT, DELETE, PATCH and OPTIONS request
curl -X DELETE  http://localhost:8080/api/demo
curl -X PUT  http://localhost:8080/api/demo
curl -X PATCH  http://localhost:8080/api/demo
curl -X OPTIONS  http://localhost:8080/api/demo

These methods will each return error code 405 – Method Not Allowed.

{
  "timestamp": "2020-01-06T20:12:26.747+0000",
  "status": 405,
  "error": "Method Not Allowed",
  "message": "No message available",
  "path": "/api/demo"
}

Summary

In this solution, we made use of a Spring Interceptorto pre-process the HTTP requests. If the request did not match our approved HTTP methods then werejected the request. In our case, we only approved HTTP GET and POST requests.

This is just a basic solution. However, if you have more advanced requirements such as access control, rate limiting, security, analytics, etc … then I would recommend an API management tools. API management tools can help you with this functionality. These tools provide this functionality out of the box and minimizes the amount of custom code you have to develop. To help you get started, you can use 3Scale. 3Scale is an open-source API Management tool.

Source code

Just a reminder, the source code is available for download: spring-rest-api-block-http-methods.zip



How To View Hibernate SQL Parameter Values

When using Hibernate, if you log the Hibernate SQL statements, you will see this:


Hibernate: insert into student (email, first_name, last_name, id) values (?, ?, ?, ?)

However, for debugging your application, you want to see the actual parameter values in the Hibernate logs. Basically, you want to get rid of the question marks in the Hibernate logs.

You can view the actual parameters by viewing the low-level trace of the Hibernate logs. This is not set up by default. However, we can add log4j to allow us to see these low-level logs.

Here is an overview of the process:

1. Add log4j to your project classpath
2. Add log4j.properties to your “src” directory


Here are the detailed steps:

1. Add log4j to your project classpath

1a. Download log4j v1.2.17 from this link:
http://central.maven.org/maven2/log4j/log4j/1.2.17/log4j-1.2.17.jar

1b. Copy this file to your project’s lib directory

bind-parameters-log4j-jar-file

1c. Right-click your Eclipse project and select Properties

1d. Select Build Path > Libraries > Add JARS…

1e. Select the log4j-1.2.17.jar file from the lib directory

bind-parameters-log4j-jar-build-path

 

2. Add log4j.properties to your “src” directory

2a. Copy the text from below

2b. Save this file in your “src” directory

bind-parameters-log4j-properties

Note: This file has an important setting:

log4j.logger.org.hibernate=TRACE

This allows you see a low-level trace of Hibernate and this allows you see the real SQL parameter values.


Now run your application. You will see a lot of low-level TRACE logs in the Eclipse Console window.

Right-click in the Eclipse Console window and select Find/Replace…

Search for: binding parameter

You will see the logs with the real parameter values. Congrats!

bind-parameters-output



JDBC and MySQL: Getting rid of the dreaded message – WARN: Establishing SSL connection without server’s identity verification is not recommended

When connecting to a MySQL database, you may encounter this scary warning message.

Thu Feb 04 14:49:25 IST 2016 WARN: Establishing SSL connection without server’s identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn’t set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to ‘false’. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification.

Your app will continue to work fine … it is just the MySQL database yelling at you.

To get rid of the warning message. Append ?useSSL=false to the end of your database connection string.

For example,

Replace – jdbc:mysql://localhost:3306/demo

With – jdbc:mysql://localhost:3306/demo?useSSL=false

Note that I appended ?useSSL=false to the end.

That will get rid of the pesky message … whew!