It has been a long time since i posted any java related blog post. Today it is a time i came up from my busy schedule. So in this post i am just only going to demonstrate how to add JWT authentication for small boot application which will use redis for saving its user’s session and information. There are many way we can use session but lets try this time with Redis as primary source for session storage.

I have my redis server in my VMWare which is opened in default port  6379. So now all i need is small spring boot application to get started. Lets start a new project with clean maven project and some dependencies essential for making JWT Token based session using redis.

1. Project Create

Here we have just added <parent> for making the project to inherit all the stuffs from the spring-boot-starter-parent. So now we have added spring-boot-starter-web, spring-boot-starter-data-redis, spring-security, jwt, jedis(redis) and lombok in our project which are essential dependency for starting our spring boot rest application with redis support.

The first thing we do is Create main Application file which will help the Spring Boot application to start.

So this is right now bare server with built-in spring security. Now lets create a small User resource which authenticated user can only view them.

2. Redis Configuration

This configuration is actually dependent on application.properties which contains the key-value map of redis params.

application.properties

These values will be extracted from spring to configure redis connection and make ConnectionFactory available within an application.

RedisConfig.java

So now all the redis part of configuration is done . There are templates and connection factory in this RedisConfig.java. Templates are used for saving and extracting the complex data in redis and connection factory is for connection pooling of redis.

 

3. JWT Implementation

For making the JWT to work we need to add two filters on every request incoming to server. The first one would be for authenticating user with their credentials (user, password) and another would be for validating their JWT token and authorizing the requested resource. But before moving to those filter lets start creating a service which helps us to generate JWT token for us and validate that token against the redis.

TokenAuthenticationService.java

If we look into addAuthentication() there we can see new JWT token is generated using the SHA encrypted password , the password is actually pulled from the system environment variable. Now for the authenticating part we are just using standard header format “Authorization: Bearer aawd383ec9930k… ” .  It just checks if there exist any record matching with the key (user:hash)  . Right now user can login with many session but in future we can do those restriction or view all the session and delete any which user wants to. So typically this service class will just create JWT Token and also validates the token which was sent on request payload header.

There is still a need of authentication part which really validates the user’s credential so lets create the part of authentication .

AuthenticationProviderImpl.java

This class will authenticate the request and create new session for user then saves that user’s data in redis for making it available for certain time interval i.e. session time. The SessionUser is the object that we save inside of redis with it’s key formatted as “username:hash” . So if you are wondering what hash() really is then its time to show you small snippet of AuthenticationTokenImpl.java. This class is just a subclass of AbstractAuthenticationToken which adds some extra parameter to be able to handle on.

 

AuthenticationTokenImpl.java

 

4. Spring Security and Request Filters

The master piece of all is the spring security which maintains all our resources to be secured and only allow after there is a valid token while doing a request. When it comes for restricting access resource in spring it comes quiet handy to manage them i.e. WebSecurityConfigurerAdapter we need to extend this class to create our own customized security.

SecurityConfiguration.java

This class’s authenticationManager() method has been overridden by our custom authentication AuthenticationProviderImpl.java . There are two filters (JWTLoginFilter, JWTAuthenticationFilter) were added for logging in and another for authenticating the existing JWT token in request. So all we did was disable default basic http security of spring and made all the resources to be available for only authenticated user and rest all are handled by Spring boot security.

 

JWTAuthenticationFilter.java

 

JWTLoginFilter.java

We are all good with the security stuffs . In these two filters we are actually calling the TokenAuthenticationService to validate the user’s request token . Now your application is already JWT compatible . Lets create a very simple resource where user can see some restricted stuffs once they are authenticated.

 

UserResource.java

This class contains some endpoints which is accessible using specified uri pattern and method type in @RequestMapping. Lets try to do some real tests with this minimal application that we have created.

 

5. Testing

i) Login

Postman testing for logging in

Postman testing for logging in

 

 

ii) Request resource using JWT token

Spring Boot with JWT authentication using Redis

Spring Boot with JWT authentication using Redis

 

 

6. Source code

For the source code it is available in github repository : spring-boot-redis-jwt

 

Please feel free to share your thoughts on this post by commenting below 🙂 Thanks