Writing an unified validation mechanism for REST APIs using Spring Boot and JSR-380

JSR-380 defines a metadata model and API for Java Bean validation. It can be used an “architectural-agnostic” way and it is particularly useful when it comes to validating the RESTful APIs (syntactic validation).

The default metadata source is @Annotations, with the ability to override and extend the metadata through the use of XML validation descriptors or custom code:

JSR-380 was finished in August, 2017 and it’s now a Java EE 8 standard. It’s also included by default in Spring Boot through the only available implementation – Hibernate Validator.

By default, JSR-380 doesn’t standardise a big list of validating @Annotations. Hibernate Validator adds a few extra, and enhances the existing ones, but it’s still not enough. As a developer working for a real world application you will probably need to write custom constraints.

That’s why i’ve compiled myself a library of common annotations (that are not in the standard or in Hibernate Validator). The library and code can be found on github under the name JBVExt (Java Bean Validation Extensions).

The project setup

The “example” project is a simple Spring Boot project. The main dependencies are:

By default the spring-boot-starter-web includes Hibernate Validator, so there’s no need to explicitly define it as a dependency.

Decorating the RESTful API

The API we are going to validate is composed by two REST web-services:

POST /user/ : For creating an user;
POST /post/ : For submitting the text;

The requestBodies are being mapped to the following two classes.

The comments describe each of the field-level constraints.

For example in the above class the field appCode needs to always start with “A” and end in “00”.

Note: The @Data, @AllArgsConstructor and @NoArgsConstructor are not related with JSR-380, but are part of Project Lombok.

In order to implement the constraints at the field level we would normally to write custom Java code. This type of code can become repetitive (and less readable) as soon the application grows.

JSR-380 proposes a new “decorative” approach. So instead to add the validation code at the controller level, we could just decorate the model layer with @Annotations.

In conclusion the CreateUserReq.java becomes:

And the CreatePostReq.java class becomes:

Creating an unified way of intercepting validation errors.

The JBVExt library contains an util method SimpleValidation.validate(…) that will throw a BeanValidationException exception the first time a constraint is violated.

So we will make each controller of our API invoke this method before doing anything else:

The next step will be define a “Global” Exception Handler that will intercept any BeanValidationException thrown from our Controllers and treat them in the same manner.

The @ControllerAdvice and @ExceptionHandler annotations (part of Spring) will become handy:

So instead of having to repeat all the try/catch code in each controller, we can define this unified strategy in a separate class, that will threat each exception (of type BeanValidationException) in the same way.

Running the code

The code is available on git:

The Spring Boot application will run by default on port 8080.

If we try to POST http://localhost:8080 with an invalid bodyRequest (as described by the JSR380 validation):

Simple authentication with Spring Boot and JWT Tokens

In the following article I am going to prove how you can secure a REST API (developed with Spring Boot) with JWT tokens. For simplicity Spring Security will not be used.

It is assumed the reader is already familiar with JWT.

Our Rest API will contain 3 endpoints, 2 public and 1 private (that can only be accepted with JWT):

  • /api/public/hello/{name} : Public web service that prints hello.
  • /api/secure/hello/{name} : Private web service that prints hello. Can only be called if the JWT token exist on the header. Otherwise returns HTTP 403.
  • /api/public/auth/ : Authentication service. Based on user/pass credentials generates and valid JWT token.

All the code is available on github:

Project is bootstrapped using Spring Initialzr together with gradle.

The generated build.gradle file is:

Observations:

  • The library that coverts the JWT functionality is called jjwt.
  • I prefer to use project lombok in my projects. It’s an useful library that can generate getters, setters, constructors, etc. through @Annotations.

We will be starting the project by defining some of the constants. A good idea is to store them in the application.properties file, so we can easily inject them at runtime using @Value annotation.

Read More