JWT(JWS) authentication for Springboot REST API application with HandlerInterceptor

Chanaka MBK
5 min readJan 18, 2021

This post will show you how to authenticate the Springboot REST API application using JWT authentication. To do this process I’m going to use a HandlerInterceptor class provided by the spring framework.

To learn more about HandlerInterceptor behavior please visit my previous post from here. Also please visit here to get the full code example.

JSON Web Token, or JWT, is a specification for the representation of claims to be transferred between two parties. The claims are encoded as a JSON object used as the payload of an encrypted structure, enabling the claims to be digitally signed or encrypted.

The containing structure can be JSON Web Signature (JWS) or JSON Web Encryption (JWE).

In this post, I'm going to talking about JWS. If you want to know about JWE, visit my blog post about the JWE token.

Overview

JSON Web Token is an Internet standard for creating data with optional signature and/or optional encryption whose payload holds JSON that asserts some number of claims. The tokens are signed either using a private secret or a public/private key.

Basically, we are using JWT for Authorization and Information exchange between 2 different places.

JSON Web Token has a standard structure with consist of three parts separated by dots(‘.’).

JWS structure with the component

The main three parts are Header, Payload, and Signature. For more details please visit JWT's official site(https://jwt.io/introduction).

To explain this process, I will use 2 controllers called Create Employee and Retrieve Employee with HandlerInterceptor class. Please refer to the following sequence diagrams to get a better idea of the JWT authentication.

JWS flow with the CRUD operations

Technologies

Java 1.8
Maven 3.6.1
Springboot 2.2.7.RELEASE
spring-boot-starter-web
jjwt-api
jjwt-impl
jjwt-jackson
MongoDB
log4j

Project Structure

Project Structure

STEP 1: Maven Dependency (POM.xml).

Springboot web dependency for HandlerInterceptorAdapter
JWT related dependencies

Please visit pom.xml to see the completed version.

STEP 2: Add a customized Interceptor class.

Here we are using HandlerInterceptorAdapter class to make our custom Interceptor class called EmployeeSecurityInterceptor.Since we are only going to validate application credentials, override preHandle() method only. Also, we have overridden postHandle() method with some logs.

In this preHandle() method we are doing a couple of things like,
- Get JWT token from the header value.
- Fetching AUTH token public key from the resource folder.
- Validate JWT token using the public key.

EmployeeSecurityInterceptor.java

Please go through EmployeeSecurityInterceptor class, I have explained each step in the comment section. To learn more about HandlerInterceptor behavior please visit my previous post from here.

STEP 3: Configuration.

We will add a configuration class for the Spring MVC configuration since we must bind our custom Interceptor class with Spring MVC.
Here we have a class called SpringMVCConfig and it’s overridden by WebMvcConfigurer provided by the Spring framework. Also, we can include /exclude our project controllers according to our requirements. Let's say we need to skip the interceptor layer for a few controllers. Then we can use the ‘excludePathPattern’ method as I mentioned below example.

SpringMVCConfig.java

Also, our public key and private key are stored under the folder called auth-keys were in the resource folder. Here we need only the public key to do this auth validation.

STEP 4: Service layer changes.

Here I have introduced a couple of classes to act as an auth service module. Inside of this service layer, we are doing a couple of things.

1) getAuthPublicKey()

Here we are fetching a public key file from our resource folder. But in real scenarios normally keep this file in a secured place like a secured S3 bucket, AWS secret manager, GCP secret manager, etc. Once retrieved from the file, it is coming as a String object. So we have to convert it into the PublicKey type.

2) convertToPublicKey()

Retrieved String object converts into PublicKey type.

3) validateJwtToken()

Validate JSON web token(Coming with request header) with PublicKey.Here JWT provides different types of claims.

In this example, I’m using iss,exp, and nbf to validate the token.
Please visit the official JWT site(https://jwt.io/introduction) to see more information about claims.

Please visit AuthServiceImpl to see the full implementation.

STEP 5: Generate JWT(JWS) token

Please visit this example to see the JWS token generation. I have explained all steps in the comment section. Once you went through this example code you can get a proper idea about JWS token generation.

Generate JWS Token

STEP 6: Testing

Once you are done with the changes you can test both endpoints using Postman.

If the validation method returns TRUE, the request will redirect the controller endpoint according to the URI with a 200 (OK ) status.
If it returns FALSE, then it will throw an error with 401(UN-AUTHORIZED) status.

Example Request :

Set JWT token as an auth header value
Request body

Success Response

Success Response with valid JWT token

Failed Response

Failed Response with invalid JWT token

Please visit a completed version from here and I have explained every possible step in the comment section. Please leave a comment if you have concerns or questions.

--

--

Chanaka MBK

Experienced Software Engineer with a demonstrated history of working in the information technology and services industry. Skilled in JAVA,Spring Boot, Angular.