11.3 JWT Architecture Basics
In modern REST API servers, a Stateless authentication method using JWT (JSON Web Token) is commonly used instead of sessions for better scalability.
1. Structure of JWT
A JWT consists of three parts separated by dots (.):
- Header: Information about the token type and the hashing algorithm used (e.g., HS256).
- Payload: The actual data (Claims), such as user ID, permissions, and expiration time.
- Signature: Created by combining the Header and Payload with a secret key known only to the server.
2. JWT Authentication Flow
- The user sends a login request.
- The server verifies credentials, issues a JWT, and sends it back.
- The client includes the token in the HTTP Authorization Header as
Bearer <token>for subsequent requests. - The server verifies the token signature and extracts user information to treat them as an authenticated user.
3. Why Use JWT?
- Stateless: The server doesn't need to maintain client state (session), making it easier to scale.
- Decoupled: Efficient in microservices architectures where authentication and resource servers are separated.
- Security: Data tampering can be quickly detected using the Signature.
4. Integrating JWT with Spring Security
In a JWT-based approach, you must disable sessions and add a custom JwtFilter to the chain.
// Part of SecurityConfig configuration
http
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
.addFilterBefore(new JwtAuthenticationFilter(tokenProvider), UsernamePasswordAuthenticationFilter.class);
🎯 Key Points
- JWT consists of Header, Payload, and Signature.
- Unlike session-based auth, it is a Stateless method where the server stores no state.
- Setting SessionCreationPolicy.STATELESS in Spring Security configuration is essential.