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