JWT Authentication
JWT (JSON Web Token) is a signed, compact credential.
Introduction
JWT (JSON Web Token) is a signed, compact credential. For Orders APIs, the common pattern is: login issues a short-lived access token; the client sends Authorization: Bearer <token> on each request; the resource server validates signature and claims without a server session.
On Boot 3, prefer spring-boot-starter-oauth2-resource-server with oauth2ResourceServer(o -> o.jwt(...)) on the SecurityFilterChain. That is the Security 6 way — not custom filter hacks copied from outdated blogs.
A JWT has header, payload, and signature. Payload claims include sub, roles/authorities, iat, and exp. Keep access tokens short-lived; pair with refresh tokens in the next lesson.
Never paste real signing secrets into lessons or repos — use placeholders like ${JWT_PRIVATE_KEY}.
Purpose of this lesson
Issue and validate JWT bearer access tokens for a stateless Orders API using Security 6 resource-server support.
Understanding the topic
Bearer access token = self-contained signed claims.
- Access token: short TTL (minutes), sent as Bearer on API calls.
- Claims: subject, roles, expiry — keep payloads small.
- Signature: HMAC or asymmetric (RS256/PS256); asymmetric eases key distribution.
- Resource server: validates JWT and builds Authentication.
- Stateless:
SessionCreationPolicy.STATELESSwith the chain.
Step-by-step explanation
- Add
spring-boot-starter-oauth2-resource-server. - Configure JWT decoder via JWK set URI or key location using env placeholders.
- Wire
.oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults()))on the chain. - Implement a login/issuer path that returns an access token (and later a refresh token).
Syntax reference
JWT shape (conceptual payload).
header.payload.signature{"sub": "cust-42","roles": ["USER"],"iat": 1730000000,"exp": 1730000900}
Informative example
Resource-server chain + simple issuer sketch.
@BeanSecurityFilterChain api(HttpSecurity http) throws Exception {return http.csrf(csrf -> csrf.disable()).sessionManagement(s -> s.sessionCreationPolicy(SessionCreationPolicy.STATELESS)).authorizeHttpRequests(auth -> auth.requestMatchers("/api/auth/**").permitAll().anyRequest().authenticated()).oauth2ResourceServer(oauth2 -> oauth2.jwt(Customizer.withDefaults())).build();}@Servicepublic class JwtIssuer {private final JwtEncoder encoder;public JwtIssuer(JwtEncoder encoder) {this.encoder = encoder;}public String issueAccessToken(String subject, List<String> roles) {Instant now = Instant.now();JwtClaimsSet claims = JwtClaimsSet.builder().subject(subject).claim("roles", roles).issuedAt(now).expiresAt(now.plusSeconds(900)).build();return encoder.encode(JwtEncoderParameters.from(claims)).getTokenValue();}}# application.yml (placeholders only)# spring.security.oauth2.resourceserver.jwt.jwk-set-uri: ${JWK_SET_URI}
Real-world use
TechLearningPRO mobile and web clients call the same Orders API. JWTs let each instance validate tokens locally with the public JWK set, so checkout scales horizontally without sticky sessions. Short TTLs limit damage if a token leaks from a device log.
Security implications
Stolen JWTs are bearer credentials until expiry.
- Transmit only over TLS.
- Do not store access tokens in insecure browser storage when cookie patterns fit better.
- Rotate signing keys; configure JWK sets for rotation.
Best practices
- Prefer asymmetric algorithms so APIs hold only public keys.
- Access tokens measured in minutes; refresh handled separately.
- Map roles/authorities explicitly via a JWT authentication converter when claim names differ.
Common mistakes
- Putting passwords or PII into JWT claims.
- Hour-long access tokens without refresh rotation.
- Hand-rolling JWT parse/verify instead of the resource-server stack.
Advanced interview questions
Interview Prep
Practice concise answers, then expand each card for the explanation.
1BeginnerQuestionWhy are JWTs popular for APIs?+
Answer
2BeginnerQuestionWhat does Authorization: Bearer mean?+
Answer
3IntermediateQuestionHMAC vs asymmetric signing for JWT?+
Answer
Hands-on exercise
Lab. Protect /api/orders/** with JWT resource server. Call with a missing header (401), then with a Bearer access token from your issuer (200).
Summary
Orders APIs validate bearer JWTs via the resource-server filter chain. Next: refresh tokens for lasting sessions without long-lived access tokens.