A simple Spring Boot application demonstrating JWT (JSON Web Token) authentication using Aspect-Oriented Programming (AOP).
This project showcases how to implement JWT-based authentication in a Spring Boot application using AOP. The application intercepts all REST controller method calls and validates the JWT token provided in the request header.
- Java 21
- Spring Boot 3.2.10
- Spring AOP
- JJWT (JSON Web Token for Java) 0.11.5
- JUnit 5 for testing
- Maven for dependency management
- JWT token generation and validation
- AOP-based authentication for all REST endpoints
- Simple Hello World REST API
- Java 21 or higher
- Maven 3.6 or higher
git clone https://github.com/edwin/spring-boot-and-jwt.git
cd spring-boot-and-jwtmvn clean installmvn spring-boot:runThe application will start on port 8080 by default.
GET /
Returns a simple "Hello World!" message in JSON format.
Example response:
{
"message": "Hello World!"
}Note: All endpoints require a valid JWT token in the request header.
All REST endpoints in this application are protected by JWT authentication. To access any endpoint, you need to include a valid JWT token in the request header.
Include the JWT token in the my_token header of your HTTP request:
my_token: <your_jwt_token>
The JWT token contains the following claims:
- Subject: Username
- Custom claim "username": Username
- Issued At: Token creation time
- Expiration: Token expiration time (1 hour after creation by default)
- Access tokens expire after 1 hour (3600000 milliseconds)
- Refresh tokens expire after 24 hours (86400000 milliseconds)
Run the tests using Maven:
mvn testThe project includes comprehensive tests for JWT token generation and validation.
Located in src/test/java/com/edw/JwtUtilsTest.java, this test class verifies the functionality of the JWT utility class:
- Token Generation: Tests that tokens are correctly generated with proper claims
- Token Validation: Validates that the system correctly identifies:
- Valid tokens
- Invalid/malformed tokens
- Empty tokens
- Expired tokens
Located in src/test/java/com/edw/controller/HelloWorldControllerTest.java, this test class verifies the REST API functionality:
- Authentication Testing: Verifies that accessing the endpoint without a JWT token returns HTTP 500
- Endpoint Functionality: Confirms that accessing the endpoint with a valid JWT token returns HTTP 200 and the correct "Hello World!" message
The application configuration is in src/main/resources/application.properties:
spring.application.name=spring-boot-and-jwt
server.port=8080
# logging
logging.level.root=INFO
logging.level.com.edw=DEBUGMuhammad Edwin