If you ever wanted to secure your brilliant REST API with Spring Boot but Spring Security felt too confusing, badly documented and a little overkill for the simple stuff you want to do, you can create a simple, stateless, authentication mechanism for your services using JWT Tokens.

As a proof of concept on how we are going to integrate the JWT tokens with our Spring Boot Rest api we are going to create three REST services:

  • /api/public/hello/{name} : This will be a public web service that will say hello without discrimination;
  • /api/secure/hello/{name} : This will perform the same operation as the service above, but it will be callable only by authenticated users. Otherwise it will return 401 Unauthorised. Or 406 Not Acceptable if somebody is trying to hack into your tokens :);
  • /api/public/auth/ : This service will allow the users of your API to authenticate with it.

The code can be found also on github:

Our project will be built using Spring Initialzr together with gradle. Our build.gradle file for the project will eventually look like this.

Observations:

  • The library that implements the JWT part is called jjwt and can be found here.
  • I prefer to use project lombok in my projects. It’s a cool little library that generates getters/setters/constructors/builders and other neat stuff through the use of annotations.

A good idea for the project is to keep some of the configurable properties like the time to live for the token, the authentication header and the secret key in the Spring Boot application.properties file.

They can easily be “injected” in our code at a later time using the @Value annotation.

Continue reading