Define data models for user management, and handle token expiration and renewal efficiently
Explore the docs »
View Demo
·
Report Bug
·
Request Feature
Table of Contents
"Project User System JWT Token And Refresh Token Authenticate" is a Java Spring Framework backend application designed for secure user authentication. It encompasses a comprehensive set of features including user signup and login functionalities. Utilizing JSON Web Tokens (JWT), the system ensures secure communication between the client and server, while also implementing token refresh mechanisms to maintain user sessions. This project further illustrates the configuration of Spring Security to seamlessly integrate JWT authentication, define data models for user management, and handle token expiration and renewal efficiently. Through these implementations, the project showcases best practices for building robust and secure authentication systems in Java Spring applications.
The main functionalities of the "Project User System JWT Token And Refresh Token Authenticate" project include:
-
User Signup: Allows users to register for an account by providing necessary information such as username, email, and password.
-
User Login with JWT Authentication: Provides users with the ability to securely authenticate themselves using their registered credentials. Upon successful authentication, the server issues a JSON Web Token (JWT) to the client.
-
Configuration of Spring Security with JWT: Integrates Spring Security framework to handle user authentication and authorization using JWT tokens.
-
Data Models and Associations: Defines data models and their associations to manage user authentication and authorization data effectively.
-
JWT Token Generation: Generates JWT tokens upon successful user authentication, containing relevant user information and expiration time.
-
JWT Refresh Token: Implements a mechanism to issue refresh tokens along with JWT tokens, allowing users to obtain new access tokens without re-authenticating after the expiration of the current token.
-
Token Expiration and Renewal: Manages token expiration by implementing mechanisms to renew access tokens using refresh tokens and HttpOnly cookies, ensuring uninterrupted user sessions and enhanced security.
This section should list any major frameworks/libraries used to bootstrap to this project. Leave any add-ons/plugins for the acknowledgements section. Here are a few examples.
This guide will help you set up and run the "Project User System JWT Token And Refresh Token Authenticate" project locally.
- JDK (Java Development Kit) installed on your system
- Maven build tool installed
- MySQL database installed and running
- Your favorite code editor or IDE (Integrated Development Environment)
-
Clone the Repository: Clone the project repository from GitHub using the following command:
git clone <repository_url>
-
Navigate to Project Directory: Move into the project directory using the cd command:
cd <project_directory>
-
Configure MySQL Database: Set up your MySQL database and configure the database properties in the
$ application.properties
file located in the$ src/main/resources
directory. -
Build the Project: Use Maven to build the project:
mvn clean install
-
Run the Application: Execute the generated JAR file to run the application:
java -jar target/<generated_jar_file>.jar
-
Access the Application: Once the application is running, you can access the endpoints for user signup and login using tools like Postman or cURL.
- Database Connection: If the backend can't connect to the database, check your MySQL service and ensure the credentials in
$ application.properties
are correct. - Port Conflicts: If you encounter port conflicts (e.g., if port 8080 or 3000 is already in use), you can change the port in the backend's
$ application.properties
file$ (server.port=yourNewPort)
and the frontend's$ .env
file, if applicable. - Dependencies: If you face issues with missing or incompatible npm packages, ensure you've run
$ npm install
from within the frontend directory and that your$ package.json
file is correctly set up.
- Use the provided endpoints for user signup and login to authenticate users and obtain JWT tokens.
- Test the token expiration and renewal mechanisms to ensure seamless user sessions.
- Customize the application properties in the
$ application.properties
file to suit your environment and requirements. - Explore and modify the source code to extend the functionality or integrate additional features.
# Set up DataBase Connection - mongoDB
spring:
datasource:
url: jdbc:sqlserver://THIEN-PHU:1433;databaseName=ProjectJWTTokenAndRefreshToken;encrypt=false
driverClassName: com.microsoft.sqlserver.jdbc.SQLServerDriver
username: sa
password: 123456789Thien_Phu
jpa:
hibernate:
ddl-auto: update
properties:
hibernate:
dialect: org.hibernate.dialect.SQLServerDialect
show-sql: true
---
# Set up JWT Token
Kelvin:
app:
jwtSecret: "7NNdHNWWbyUK0AjbPCovcFEmzTcnC9CUwzCBZvrXl7irVN2zijJCVrJHEHhzvoZpCExEwEMj9w3r1ADrzbGFGZsULb3gsSk0n7Rp2vH1MjF3VdGIlhcN0WJSGbWJ5jyp"
jwtExpirationMs: 3600000
jwtRefreshExpirationMs: 86400000
Start by creating controllers for user signup and login functionalities.
Define endpoints to handle user requests, such as $ /api/auth/signup
for user registration and $ /api/auth/login
for user authentication.
@PostMapping("/signup")
public ResponseEntity<?> registeruser(@Valid @RequestBody SignupDto signupDto){
...
}
@PostMapping("/signin")
public ResponseEntity<?> authenticateUser(@Valid @RequestBody SigninDto signinDto){
...
}
Configure Spring Security to work with JWT tokens by creating a $ SecurityConfig
class.
Define security rules and access permissions for different endpoints using annotations like $ @EnableWebSecurity
and $ @EnableGlobalMethodSecurity
.
@Bean
public DaoAuthenticationProvider authenticationProvider() {
DaoAuthenticationProvider authProvider = new DaoAuthenticationProvider();
authProvider.setUserDetailsService(userDetailsService);
authProvider.setPasswordEncoder(passwordEncoder());
return authProvider;
}
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authConfig) throws Exception {
return authConfig.getAuthenticationManager();
}
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http.csrf(csrf -> csrf.disable())
.exceptionHandling(exception -> exception.authenticationEntryPoint(unauthorizedHandler))
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.authorizeHttpRequests(auth ->
auth.requestMatchers("/api/auth/**").permitAll()
.requestMatchers("/api/test/**").permitAll()
.anyRequest().authenticated()
);
http.authenticationProvider(authenticationProvider());
http.addFilterBefore(authenticationJwtTokenFilter(), UsernamePasswordAuthenticationFilter.class);
return http.build();
}
- Implement JWT token generation and validation logic in the
$ JwtUtils class
. - Generate a JWT token upon successful user authentication, including user details and expiration time.
- Implement a mechanism to generate and store refresh tokens securely.
@Component
public class JwtUtils {
@Value("${jwt.secret}")
private String secret;
@Value("${jwt.expiration.ms}")
private int jwtExpirationMs;
public String generateJwtToken(Authentication authentication) {
UserDetailsImpl userPrincipal = (UserDetailsImpl) authentication.getPrincipal();
return Jwts.builder()
.setSubject((userPrincipal.getUsername()))
.setIssuedAt(new Date())
.setExpiration(new Date(new Date().getTime() + jwtExpirationMs))
.signWith(SignatureAlgorithm.HS512, secret)
.compact();
}
// Other methods for token validation, extraction, etc.
}
Roadmap for Project User System JWT Token And Refresh Token Authenticate
-
Setup Project Structure:
- Define project directory structure.
- Initialize Git repository.
- Set up Maven for dependency management.
-
Implement User Authentication:
- Create user entity and repository.
- Implement user signup and login functionality.
- Configure Spring Security for basic authentication.
-
Integrate JWT Authentication:
- Add dependencies for JWT token generation.
- Configure JWT token provider and authentication filter.
- Implement token generation and validation logic.
-
Implement Refresh Token Mechanism:
- Define refresh token entity and repository.
- Implement refresh token generation and storage.
- Integrate refresh token with JWT authentication.
-
Configure Security with JWT:
- Secure endpoints using JWT token authentication.
- Customize security configurations for different endpoints.
- Implement role-based access control using JWT claims.
-
Handle Token Expiration and Renewal:
- Implement token expiration mechanism.
- Configure token renewal using refresh tokens.
- Test token expiration and renewal scenarios.
-
Enhance Error Handling and Logging:
- Implement error handling for authentication failures.
- Add logging for authentication and authorization events.
- Customize error responses for better user feedback.
-
Implement User Management Features:
- Add endpoints for user profile management.
- Implement password reset functionality.
- Develop user role management features.
-
Testing and Validation:
- Write unit tests for authentication and authorization logic.
- Conduct integration tests for API endpoints.
- Validate token generation, expiration, and renewal processes.
-
Documentation and Deployment:
- Document API endpoints and usage examples.
- Provide instructions for setting up and configuring the project.
- Prepare the application for deployment to production environment.
-
Review and Optimization:
- Perform code review and refactor where necessary.
- Optimize performance of authentication and token management.
- Ensure compliance with best practices and security standards.
-
Future Enhancements:
- Explore additional security measures such as two-factor authentication.
- Implement audit logging for user activities.
- Integrate with external authentication providers like OAuth.
-
User Signup Endpoint:
-
User Login Endpoint:
-
Access Protected Resources:
-
Use the access token obtained from the login response to access protected resources (e.g.,
/api/users/profile
). -
Add the token to the request headers with the key
Authorization
and valueBearer <access_token>
. -
Send a GET request to the protected endpoint and verify that the user's profile information is returned.
-
-
Token Expiration and Refresh:
-
Test token expiration by waiting for the access token to expire (based on the token expiration time).
-
Attempt to access a protected resource with the expired token and verify that it results in a 401 Unauthorized error.
-
Test token refresh by sending a POST request to the refresh token endpoint (
/api/auth/refresh
) with the expired access token. -
Verify that a new access token is generated and returned in the response.
-
-
Invalid Token Handling:
- Test invalid token handling by sending requests with an invalid or tampered access token.
- Verify that the server responds with a 401 Unauthorized error and prompts the user to log in again.
-
Logout Endpoint:
- Test the logout functionality by sending a POST request to the logout endpoint (
/api/auth/logout
). - Verify that the user's session is invalidated, and the access token is no longer accepted for authentication.
- Test the logout functionality by sending a POST request to the logout endpoint (
-
Error Handling:
- Test various error scenarios (e.g., invalid input, server errors) and verify that the API returns appropriate error responses with descriptive error messages.
-
Additional Testing:
- Perform additional testing based on specific use cases and edge cases relevant to your application's requirements.
- Test different user roles and permissions to ensure proper access control and authorization.
Contributions are what make the open-source community such an amazing place to learn, inspire, and create. Any contributions you make are greatly appreciated.
- Fork the repository.
- Clone the forked repository to your local machine.
git clone https://github.com/your-username/Project-FullStack-Employee-System-CRUD.git
- Create a new branch for your feature or bug fix.
git checkout -b feature/your-feature-name
- Make changes to the codebase.
- Test your changes thoroughly.
- Commit your changes.
git commit -m "Add your commit message here"
- Push your changes to your fork.
git push origin feature/your-feature-name
- Create a new Pull Request from your forked repository to the original repository.
- Provide a descriptive title and detailed description for your Pull Request.
- Wait for maintainers to review your Pull Request and address any feedback if necessary.
- Once approved, your changes will be merged into the main project.
- Follow the project's coding style and guidelines.
- Ensure your code is well-tested.
- Provide detailed and clear commit messages.
- Be respectful to others and their contributions.
- If you're unsure about something, don't hesitate to ask for clarification or guidance.
If you encounter any bugs or have suggestions for new features, please open an issue on GitHub. Provide detailed information about the problem or feature request, including steps to reproduce for bugs.
Huynh Thien Phu - @kelvin_hnh - [email protected]
Project Link: https://github.com/your_username/repo_name
We would like to express our gratitude to the following individuals and organizations for their contributions to this project:
- Open Source Community: For providing a wealth of knowledge and resources to the community.
- Stack Overflow: For being an invaluable resource for troubleshooting and problem-solving.
- GitHub: For providing an excellent platform for collaboration and version control.
- ReactJS Documentation: For comprehensive documentation and tutorials on ReactJS.
- Spring Framework Documentation: For extensive documentation and guides on the Spring Framework.
- Bootstrap Documentation: For clear and concise documentation on Bootstrap.
- Axios Documentation: For detailed documentation and examples on Axios.
- MySQL Documentation: For comprehensive documentation on MySQL.