Skip to main content
Advertisement

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 (.):

  1. Header: Information about the token type and the hashing algorithm used (e.g., HS256).
  2. Payload: The actual data (Claims), such as user ID, permissions, and expiration time.
  3. Signature: Created by combining the Header and Payload with a secret key known only to the server.

2. JWT Authentication Flow

  1. The user sends a login request.
  2. The server verifies credentials, issues a JWT, and sends it back.
  3. The client includes the token in the HTTP Authorization Header as Bearer <token> for subsequent requests.
  4. 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.
Advertisement