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

    Refresh Tokens

    Access tokens should expire quickly.

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

    Introduction

    Access tokens should expire quickly. When they do, clients use a longer-lived refresh token to obtain a new access token without re-entering credentials.

    Refresh tokens are not JWTs-by-requirement. Many Orders deployments store an opaque random token (hashed) in the database, bind it to a user and device family, and rotate it on every use.

    Rotation + reuse detection matters: if a stolen refresh token is used after the legitimate client already rotated, revoke the entire family.

    Keep access tokens in memory where possible; treat refresh tokens as high-value secrets — httpOnly Secure cookies for browsers, secure storage on mobile.

    Purpose of this lesson

    Design rotating refresh tokens so Orders clients renew short-lived JWT access tokens safely.

    Understanding the topic

    Short access + rotating refresh = UX without long-lived bearers.

    • Access token: minutes; authorizes API calls.
    • Refresh token: days; only accepted at the token endpoint.
    • Rotation: issue a new refresh on each successful refresh call.
    • Reuse detection: presenting an old refresh after rotation signals theft.
    • Revocation: logout and password change invalidate the family.

    Step-by-step explanation

    1. On login, persist a hashed refresh token with user id, expiry, and family id.
    2. Return access JWT + refresh token (body or cookie — pick one model).
    3. Implement POST /api/auth/refresh that validates, rotates, and returns a new pair.
    4. On logout, delete or mark revoked all tokens in the family.

    Syntax reference

    Happy-path refresh flow.

    text
    Client Auth (/api/auth) Orders API
    | login | |
    |----------------------->| |
    | access + refresh | |
    |<-----------------------| |
    | API + Bearer access | |
    |-------------------------------------------------->|
    | ... access expired ... |
    | POST /refresh (refresh) |
    |----------------------->| |
    | new access + refresh | |
    |<-----------------------| |

    Informative example

    Opaque refresh record and rotate sketch.

    java
    public record RefreshSession(
    String familyId,
    String tokenHash,
    String userId,
    Instant expiresAt,
    boolean revoked) {}
    @Service
    public class RefreshService {
    private final RefreshSessionRepository sessions;
    private final JwtIssuer jwtIssuer;
    private final PasswordEncoder hasher; // or dedicated token hasher
    public TokenPair refresh(String presentedRaw) {
    String hash = sha256(presentedRaw);
    RefreshSession current = sessions.findByTokenHash(hash)
    .orElseThrow(() -> new BadCredentialsException("invalid_refresh"));
    if (current.revoked() || current.expiresAt().isBefore(Instant.now())) {
    sessions.revokeFamily(current.familyId());
    throw new BadCredentialsException("invalid_refresh");
    }
    sessions.revoke(current.tokenHash());
    String newRaw = randomToken();
    sessions.save(new RefreshSession(current.familyId(), sha256(newRaw),
    current.userId(), Instant.now().plus(7, ChronoUnit.DAYS), false));
    String access = jwtIssuer.issueAccessToken(current.userId(), List.of("USER"));
    return new TokenPair(access, newRaw);
    }
    }

    Real-world use

    TechLearningPRO mobile users stay signed in for a week, but access JWTs last fifteen minutes. Refresh rotation lets the app renew quietly. When a refresh token leaked from a backup, reuse detection revoked the family and forced a clean login — containing the blast radius.

    Security implications

    Refresh tokens are long-lived credentials.

    • TLS only; never log raw refresh values.
    • Reuse detection should revoke the whole family.
    • Password change and logout must invalidate outstanding refresh sessions.

    Best practices

    • Hash refresh tokens at rest; treat them like passwords.
    • Bind to device/family ids for targeted revocation.
    • Prefer httpOnly + Secure + SameSite cookies for browser refresh when the architecture allows.

    Common mistakes

    • Storing refresh tokens in plaintext in the database.
    • Never rotating — stolen refresh works until hard expiry.
    • Sending refresh tokens to every API host instead of only the auth token endpoint.

    Advanced interview questions

    Interview Prep

    Practice concise answers, then expand each card for the explanation.

    3 questions
    1BeginnerQuestionWhy not make access tokens last a week?+

    Answer

    A stolen access token would remain valid too long; short TTL limits exposure while refresh restores UX.
    2IntermediateQuestionWhat is refresh rotation?+

    Answer

    Each refresh issues a new refresh token and invalidates the previous one, enabling reuse detection.
    3IntermediateQuestionOpaque refresh vs JWT refresh?+

    Answer

    Opaque server-side tokens are easier to revoke and rotate centrally; JWT refresh still needs server state for reliable revocation.

    Hands-on exercise

    Lab. Implement login + refresh + logout for Orders. Refresh once successfully, then replay the old refresh token and confirm the family is revoked.

    Summary

    Refresh tokens keep Orders clients signed in without long-lived bearer access tokens. Next: structuring permissions with RBAC.

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