Overview
EduTec Backend implements a stateless authentication system using JSON Web Tokens (JWT). This approach eliminates the need for server-side session storage, making the API scalable and suitable for distributed environments.The application uses jjwt library version 0.11.5 for JWT operations, providing modern cryptographic standards and comprehensive token management.
Authentication Flow
The authentication process follows these steps:- Client sends credentials to
/auth/login - Controller receives and extracts the
LoginRequestDTO - Controller delegates token generation to
JwtService - Service creates a signed JWT with username and expiration
- Token is returned to the client as a plain string
- Client includes token in subsequent requests via
Authorizationheader
JWT Service Implementation
TheJwtService class handles all token operations using the JJWT library.
Service Configuration
- @Service Annotation
- SECRET_KEY
- KEY
Marks this class as a Spring-managed service component, making it available for dependency injection throughout the application.
Token Generation
ThegenerateToken() method creates a signed JWT containing the username and expiration time:
Token Claims
Subject (sub)
Subject (sub)
Value: Username provided during loginPurpose: Identifies the user this token belongs toThe subject is the primary identifier stored in the token. Subsequent requests can extract this to determine which user is making the request.
Issued At (iat)
Issued At (iat)
Value: Current timestamp in millisecondsPurpose: Records when the token was createdUseful for auditing, token refresh logic, and debugging authentication issues.
Expiration (exp)
Expiration (exp)
Value: Current time + 10 hours (36,000,000 milliseconds)Purpose: Defines token validity periodCalculation breakdown:
1000ms = 1 second* 60= 1 minute* 60= 1 hour* 10= 10 hours
Tokens automatically become invalid after 10 hours, requiring users to re-authenticate. This balance between convenience and security can be adjusted based on your requirements.
Signature
Signature
Algorithm: HMAC-SHA256 (HS256)Key: Pre-computed The signature ensures:
KEY from the secret- Integrity: Token data hasn’t been modified
- Authenticity: Token was issued by this server
- Non-repudiation: Only holders of the secret key can create valid tokens
HMAC-SHA256 is a symmetric algorithm, meaning the same key signs and verifies tokens. For asymmetric scenarios (microservices, distributed systems), consider RSA or ECDSA algorithms.
Token Format
Generated tokens follow the standard JWT format:- Header: Algorithm and token type (Base64 encoded)
- Payload: Claims including subject, issued at, expiration (Base64 encoded)
- Signature: HMAC-SHA256 signature to verify integrity
Auth Controller
TheAuthController provides the public API endpoint for authentication.
Login Endpoint
POST /auth/login
Request Body:
200 OK
The controller currently logs authentication attempts to the console. Consider using a proper logging framework (SLF4J/Logback) for production applications.
Login Request DTO
TheLoginRequest class structures incoming authentication requests:
username- User’s unique identifierpassword- User’s password (currently not validated)
Spring automatically deserializes JSON request bodies into this DTO using Jackson. The empty constructor is required for this process.
Security Best Practices
Current Implementation Gaps
Recommended Enhancements
1. Implement Password Verification
1. Implement Password Verification
Add a
UserService to authenticate credentials:2. Add Token Validation Filter
2. Add Token Validation Filter
Create a filter to verify JWTs on protected endpoints:Add validation methods to
JwtService:3. Externalize Secret Key
3. Externalize Secret Key
Move the secret to Update
application.properties:JwtService:4. Add Input Validation
4. Add Input Validation
Use Bean Validation annotations:Update controller:
5. Use BCrypt for Passwords
5. Use BCrypt for Passwords
Hash passwords before storing in the database:Update
User entity:Token Usage Example
Once implemented, clients should include tokens in theAuthorization header:
Dependencies
The JWT implementation relies on these libraries frompom.xml:109-125:
- jjwt-api: Core JWT API and interfaces
- jjwt-impl: Implementation of JWT specification
- jjwt-jackson: JSON processing using Jackson library
Spring Security starter (
spring-boot-starter-security) is commented out in the POM file, indicating a lightweight custom authentication approach without the full Spring Security framework.Next Steps
- Database - Learn about the User entity and data persistence
- Architecture - Understand the overall system design
- API Reference - Explore all available endpoints