This project demonstrates how to create a custom annotation in a Spring Boot application while implementing JWT-based authentication. The custom annotation @InjectUserContext
allows automatic injection of user details (like username and roles) into API methods, simplifying authentication and authorization workflows. The project also includes:
- Spring Security for authentication and authorization.
- JWT (JSON Web Token) for secure API access.
- H2 in-memory database for easy testing.
- Aspect-Oriented Programming (AOP) to handle the custom annotation.
- Global Exception Handling for better error management.
It is a complete authentication system that demonstrates best practices for user authentication and role-based access control in Spring Boot.
Now that your project is set up correctly, follow these step-by-step instructions to run and test your application.
Before running the project, make sure you have:
- ✅ Java 17 (or the version specified in
pom.xml
) - ✅ Maven Installed (
mvn -v
to check) - ✅ IntelliJ IDEA / VS Code / Eclipse (Any Java IDE)
- ✅ Postman / cURL (for API testing)
- Open the project in IntelliJ IDEA (or your preferred IDE).
- Navigate to the
CustomAnnotationApplication.java
class. - Click Run
▶️ OR use the shortcut:
Mac: Cmd + Shift + F10
Windows/Linux: Ctrl + Shift + F10
Run the following commands in the project root directory:
# 1️⃣ Clean previous builds (optional)
mvn clean
# 2️⃣ Build the project
mvn install
# 3️⃣ Run the application
mvn spring-boot:run
Your Spring Boot application should now start on http://localhost:8080
.
Since we are using H2 in-memory database, you can check the database via H2 Console:
- URL:
http://localhost:8080/h2-console
- JDBC URL:
jdbc:h2:mem:testdb
- Username:
sa
- Password:
password
Click Connect to view the users
table.
Now let's test your APIs using Postman or cURL.
{
"username": "admin",
"password": "admin123"
}
{
"token": "eyJhbGciOiJIUzI1NiIsInR5..."
}
✅ Copy this token for the next requests.
Authorization: Bearer <PASTE_YOUR_JWT_HERE>
{
"username": "admin",
"roles": "ROLE_ADMIN"
}
If you don’t send a token, you should get:
{
"error": "Unauthorized"
}
✅ This confirms that the JWT authentication and custom annotation are working.