Spring Boot Tutorial 0/110 lessons ~6 min read Lesson 41

    JWT Authentication

    JWT (JSON Web Token) is a signed, compact credential.

    Course progress0%
    Focus
    13 guided sections
    Practice signal
    Examples included
    Career prep
    Interview Q&A included

    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.STATELESS with the chain.

    Step-by-step explanation

    1. Add spring-boot-starter-oauth2-resource-server.
    2. Configure JWT decoder via JWK set URI or key location using env placeholders.
    3. Wire .oauth2ResourceServer(o -> o.jwt(Customizer.withDefaults())) on the chain.
    4. Implement a login/issuer path that returns an access token (and later a refresh token).

    Syntax reference

    JWT shape (conceptual payload).

    json
    header.payload.signature
    {
    "sub": "cust-42",
    "roles": ["USER"],
    "iat": 1730000000,
    "exp": 1730000900
    }

    Informative example

    Resource-server chain + simple issuer sketch.

    java
    @Bean
    SecurityFilterChain 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();
    }
    @Service
    public 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.

    3 questions
    1BeginnerQuestionWhy are JWTs popular for APIs?+

    Answer

    They are self-contained and verifiable without a shared session store, which fits horizontally scaled services.
    2BeginnerQuestionWhat does Authorization: Bearer mean?+

    Answer

    The client sends an access token in the Authorization header using the Bearer scheme for each request.
    3IntermediateQuestionHMAC vs asymmetric signing for JWT?+

    Answer

    HMAC shares one secret with every verifier; asymmetric lets verifiers use public keys while only the issuer holds the private key.

    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.

    Ready to mark this lesson complete?Track your journey across the entire course.