Spring Boot, Spring Security using JWT
Requirements
- Download the pom.xml to download all the required dependencies
- Create 2 tables in mysql DB named Users and Authorities
- 2 Entity classes are used for persistence
- Users and Authorities have one to many mapping
Steps to execute
-
Make a post request to localhost:8080/authenticate using postman with the application/json header and body as { username:user password:pass }
-
Once the user credentials are authenticated with database values, the JWT token is generated by the method jwtTokenUtil.generateToken
-
Then the JWT is sent in the response in the format eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
-
Then make a get request to localhost:8080/hello with the following header key :Authorization_Header value : Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c
-
Now the JwtrequestFilter intercepts the request and obtains the JWT from the authorization header
-
Then the extracted JWT is validated with the wtUtil.validateToken(jwt, userDetails) method in the filter
-
Once validated, the filter chaining continues and the user can access other urls as the JWT is validated
-
This JWT validation is done only once per request by the JwtrequestFilter as it extends OncePerRequestFilter
-
The Application is made stateless in the configure(HttpSecurity http) method of SecurityConfiguration class
-
This will enable the application not to store session id. Instead it is the responsibility of the client to send the signed JWT every time to the server