Securing your Spring Boot application with JWT

Hello Solvers..

In this blog post, I’m going to talk about Jason Web Token (JWT) and how we developed a secure spring boot application using JWT. I think you will be able to get a basic understanding of JWT and how to use that in a real project.

What is JWT

First, we consider what is JWT. Actually, JWT is an open standard (RFC 7519) that is a good way to exchange information securely as JSON objects between different parties. JWT is very popular in the microservice world and it is widely used in the authorization process in web apps. JWT can send via URL, POST request, HTTP header and it is very fast.

Let’s see what is authorization because you might have some doubts difference between authentication and authorization. In authentication process checks the identity of the user to provide them access to the system, simply checks who are you (By checking username, passwords, or any other methods). Usually, this process is done before authorization. In authorization process verifies whether access is allowed through policies and rules. Usually done after successful authentication.

We can use JWT to implement the authorization process in our application because nowadays JWT is widely used for the authorization process. I have implemented this process with JWT in this blog. Apart from authorization, we can use JWT for information exchanges because we can exchange information very securely using JWT.

Structure of JWT

If we consider a JWT, we can see three main parts separated by dots. These three parts are:

· Header

· Payload

· Signature

So let’s consider an example of a token to understand this three-part:

A sample JWT code

You can see a JWT, actually, a JWT token consists of an encoded version. If we decode this token we can get required information. You can understand the main three parts of the token as follows by matching colors:

Parts of the JWT

How exactly JWT work

Process of the JWT based authorization

You can understand clearly how the authorization process works with JWT from the above diagram. When you log in to the application you need to give your login credentials (Username, Password). After that server generates a JWT. Then that JWT will send to the browser and then the JWT is re-sent to the server with an authorization header. Then check the JWT signature and get user credentials from encoded JWT. If user details are correct send the required response to the user. That is how simply JWT works in the authorization process.

Implementation

Coding time…….🤩

From this section onward we are going to build simple spring boot application using JWT. Let’s get started….

I have developed simple project to demonstrate how authorization process work with JWT. First, I have created a user class inside the entity package with several attributes such as id, username, password and email.

Then I have created AuthRequest class inside the same package (Entity). In this class has mentioned all the attributes which helps to authenticate the user.

Inside the Repository package I have created UserRepository interface which is very important to handle user details. You can see inside the interface I have created an abstract method with type of User.

Inside the main class I have created a method called initUser. So in this application I created sample users by creating a list and then saved all users by using repository.

Then I have created a class called customUserDetailsService. In this class I have used Spring security features, you can see implemented UserDetailsService interface. The UserDetailsService is a core interface in Spring Security framework, which is used to retrieve the user’s authentication and authorization information. This interface has only one method named loadUserByUsername which we can implement to feed the customer information to the Spring security API.

The I have created a class JWTUtil inside the Util package. Actually this is very important class because all the JWT based implementations are implemented here. Before implement this you need to add JWT dependency in your pom file.

createToken() method is used to generate a token on successful authentication by the user. In here we can define expiration time of the token, encode algorithm likewise.

validateToken() To validate the token means to verify the request is an authenticated one and that the token is the one that was generated and sent to the user. Here, we need to parse the token for the claims such as username, password.

Then I have created JwtFilter class under JwtFilter package. The main objective in method of doFilterInternal is to filter username and token separately.

Then I have created securityConfig class with extending WebSecurityConfigurerAdapter. Here I have implemented passwordEncoder, it is return NoOpPasswordEncoder instance that means password encoder that does nothing. It is useful for testing where working with plain text passwords may be preferred.

configure method handle all the security configurations like csrf and filters.

In the controller I have created two endpoints as GET and POST. In generateToken method you can see authRequest is pass with request body. After validation generated token has returned.

If the user is authenticated and authorized person then user redirect to the Welcome page.

Testing

In this section we are going to test our application whether it works fine or not. I have used Postman for this, but you can use any API platform like Postman, Insomnia.

First we check “/authenticate” endpoint as below.

We need to provide credentials in the body, then we can send the request. After that you can see a toke is generated successfully. This token is encoded token, now let’s see what happen decode this token

You can decode JWT from their official site. when we paste generated token encoded area you can see all the details in the decode area. you can see the algorithm in the HEADER section that used to encode. You can see all the data in the PAYLOAD section.

Now let’s check our second endpoint. After we check that we can get an idea whether our authorization process success or not.

We need to send GET request here. You should provide the token that we generated previously, you can provide it in the header section. Remember, you should provide your token as Bearer token. If its success you will able to see the welcome massage. That means our authorization process is working fine.

I think you can get batter understand about how JWT is working from this blog. Thank you very much for read my post.

--

--

--

Undergraduate at university of Kelaniya, and Studies ICT in faculty of computing and technology.

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

小計算

I Can’t Believe Flutter Doesn’t Have This Yet

A keyboard

Improve Usability On Windows

Spring Boot Unit Test Annotations with Junit 5 -Controller

Unity Creating First Person and Third Person Cameras

How to use AWS Fargate and Lambda for long-running processes in a Serverless app

APY.Finance Weekly Update (8/15–8/21)

Building a self-coordinating Config Management system

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Lakshan Madhuranga

Lakshan Madhuranga

Undergraduate at university of Kelaniya, and Studies ICT in faculty of computing and technology.

More from Medium

Spring Security : Authentication Lifecycle & JWT

Microservices with Spring Boot Part 2

Custom Spring boot security with multiple profiles

Simple Spring Boot RESTful Service