This project demonstrates how to implement JWT-based authentication and authorization in a Spring Boot application.
-
User Registration
- First, register a user and obtain an
access_tokenandrefresh_token.
- First, register a user and obtain an
-
User Login
- After registering, log in to obtain a new
access_tokenandrefresh_token. - Use the
access_tokento access the protected endpoints. - If the
access_tokenexpires, it will no longer grant access to the endpoints.
- After registering, log in to obtain a new
-
Using the Refresh Token
- When the
access_tokenexpires, use therefresh_tokenobtained during login. - Pass the
refresh_tokenin the header and call therefresh_tokenendpoint. - This will generate a new
access_tokenandrefresh_token. - Use the newly created
access_tokento access the endpoints.
- When the
-
Potential Issue
- A potential issue in the current implementation is that an old
refresh_tokencan be used to obtain a newaccess_tokenandrefresh_token. - This is not ideal, and the project should be modified to prevent this from happening.
- A potential issue in the current implementation is that an old
-
Create a New Spring Boot Project
- Include the following dependencies:
- Spring Data JPA
- Spring Security
- Spring Web
- MySQL Driver
- Include the following dependencies:
-
Database Configuration
- Set up a database connection in IntelliJ IDEA.
- Update the
application.ymlfile with the correct database URL schema.
-
Create User Entity
- Define the
Usermodel as an entity with necessary roles. - Implement the
UserDetailsinterface:- Return
truein all required methods. - Return roles in the
getAuthorities()method.
- Return
- Define the
-
Create UserRepository
- Add a method
findByUsernameinUserRepository.
- Add a method
-
Create UserServiceImpl
- Implement
UserDetailsServicein theUserServiceImplclass. - Fill in the
loadUserByUsernamemethod.
- Implement
-
Add JWT Dependencies
- Add the following dependencies for JWT:
jjwt-apijjwt-jacksonjjwt-impl
- Add the following dependencies for JWT:
-
Create JwtService
- Add a
JwtServicein the service package. - Generate an RSA key from this website and store it in a variable in
JwtService.
- Add a
-
Generate Token
- Create a
generateTokenmethod to generate the JSON Web Token. - Implement a
getSigningKey()method for signing the token.
- Create a
-
Extract Claims
- Create
extractAllClaims()to extract all details from the token. - Implement
extractClaims()to extract specific properties from the payload. - Create
extractUsername()to extract the username from the token usingextractClaims().
- Create
-
Validate Token
- Implement
isValid()to validate the token:- Check the authenticated username against the username in the token.
- Verify that the token is not expired.
- Add
isTokenExpired()to check token expiration.
- Implement
-
Create JwtAuthenticationFilter
- In the
filterpackage, createJwtAuthenticationFilterextendingOncePerRequestFilter. This ensures it runs for every incoming request. - Use the service class to validate the token. If valid, authenticate the user.
- In the
-
Register JwtAuthenticationFilter
- Register
JwtAuthenticationFilterin Spring Security to indicate token-based authentication.
- Register
- Create SecurityFilterChain
- In the
configpackage, create aSecurityFilterChainto configure credentials.
- In the
-
Create AuthenticationController
- Implement
AuthenticationControllerandAuthenticationServiceto handle user registration and login. - Write methods
register()andauthenticate()in the service class.
- Implement
-
Test Endpoint
- Create a demo controller to test the endpoint.
-
Implement Logout Endpoint
- Create a logout endpoint in the application.
-
Enhance Token Management
- Before saving the token, write logic in the
register()method to find all tokens. When a user registers, they generate a token. This token is valid for one-time use to access the endpoint, after whichisLoggedOutis set to true. Invalidate the token manually after use.
- Before saving the token, write logic in the
-
Enhance isValid() Method
- In the
JwtServiceclass, update theisValid()method to check if the user is logged out before validating the token.
- In the
-
Token Expiration Concept
- Once a user registers, they receive a token to access the endpoint. After some time, if the user logs in again, a new token is generated. The old token should no longer be valid, and only the newly created token should be used.
-
Logout in SecurityConfig
- Add logout functionality in the
SecurityConfigclass. - Create a
CustomLogoutHandlersimilar toJwtAuthenticationFilter.
- Add logout functionality in the
-
Test in Postman
- Register a user and obtain a token via Postman.
- Access the logout URL with the token, which should return a 200 OK response.
-
Create Refresh Token Functionality
- Implement a
refreshToken()method in theJwtServiceto generate a new refresh token. - Update
AuthenticationResponseto return the refresh token. - Create a controller method to access the refresh token.
- Implement the
refreshToken()method inAuthenticationService.
- Implement a
This README file provides a comprehensive overview of the JWT authentication implementation in the Spring Boot project, including detailed steps for user registration, login, token validation, logout, and refresh token management.If you had any queries please contact me in email: nisanthjothi2004@gmail.com