Spring Security JWT Authentication
3 min readMar 18, 2022
JWT authentication using Spring Security.
👉 JWT working Flow:-
- JSON Web Token(JWT) is an open standard used to share security information between two parties like client and server. It follows one particular cryptographic algorithm to encrypt and decrypt the json Objects.Algorithms like Hash 512,Hash 256 , RS256 etc.
- When a user registers in an application user details are send to server. While saving the user details. we will ensure to encrypt the password while saving into the database.(BCryptPasswordEncoder)
- When a user logs in to the application details like username and password will be sent to the server. There we will be verifying the password with encrypted password. If matches we will be creating an JWT token and sent it as a response.
- After getting the JWT token we need to append the token in the header of Http request (For all secured endpoints we need to follow the same).
- The JWT token contains three parts (HEADER, PAYLOAD)are Base64-URL encoded JSON and Cryptographic Signature.
Note:- We need a secret key to encrypt and decrypt data.
🛠 Adding JWT to Spring Security:-
- To add this filter to the working flow of spring boot we need to First create JWT Utils.
JWTUtils.java
- In the above code we have all the required methods to encrypt and decrypt the Data. We are using HS512 algorithm and in the payload we have added subject as userName also includes IssuedAt(Instance ), Expiration(Instance).(few other required implementations).
Next Step:- We need implement an interface UserDetailsService in which we will write an method called loadUserByUsername and implements it.
- We can achive authorization by sending ArrayList with Authorities.
For more clarity the below User.java class
User.java
- Now we can implement our jwtFilter which will be added to out SecutityConfig.
JwtFilters
Now we can configure our securityconfig.java file like below
Securityconfig.java
- The above code also includes CORS config.
- Below addons(SecurityUtils.java) to make our work easy by knowing who is the specific user accessing the resource using jwt token.
SecurityUtils.java
After completion we can access secured endpoints using our jwt token by placing Authentication barer <token> in header of every api call with which spring boot can identify that one particular user is accessing the resource.