We can create a new spring project for JWT Token Authentication from site: start.spring.io with following dependencies:

jwt authentication

Before we start with creating JWT token and validating it, lets start with simple username password authentication. If the authentication is successful, we’ll write the code for geenrating JWT token and validating it for subsequest requests.

Okay so lets create h2 connection and input some values in DB Userdata table. And create entity for the Userdata table and repository for the same:

Now lets create UserDetailsService which will load userdata by username. CustomAuthenticationProvider which will authenticate the username and password. For this lets create an Authentication Object of ours too named UsernamePasswordAuthenticaition. Lets create CustomFilter which will filter every incoming request, and if no authentication token is present, it will validate the username password. Finally lets create ProjectConfig which will have all the bean definitions required. We have learnt all this in the prev sections so theres no point in describing the following code in detial:

CustomUserDetailsService:

UserDetailsMapper

UsernamePasswordAuthenticaition

UsernamePasswordAuthenticaitionProvider

CustomFilter

ProjectConfig

Lets test

Now lets start adding code for JWT generation and verification

The generateJwtToken() methos will gnerate a token which will have username, issue time, expiration time encoded with a secret which we have provided in the properties file.validateJwtToken() is used to first decode the input jwt if successfully decoded with the help of signature, it will validate the username.

Secret in properties file. We can provide any value for this just that it should be of 512 characters.

Lets modify the UsernamePasswordAuthenticationProvider Code to call the generateJwtToken() method whenever there is successful credentials login. We can send this token in the response header so that from next request onwards, the user can send this token in the request header instead of password.

Now lets create authentication object for Jwt and add username and jwtToken fields. JwtAuthenticationProvider will call the validateJwtToken() which will verify if the input token is valid or not.

Now lets modify out Filter to call the JwtAuthentication if token is provided in headers and Add the JwtAuthenticationProvider to Authentication Manager.

TESTING:

Lets Test. Login using username and password. The token should be generated and visible in logs .

While passing this token in the next request, there was an excpeiton generated in JwtUtil class: .

Adding the following dependency should resolve the exception.

Again call the hello endpoint by providing the jwt token and username in header. It is now successfully allowing to access the endpoint.

Leave a Reply

Your email address will not be published. Required fields are marked *