JWT access and refresh tokens in Spring Security

A JWT lets an API check who is calling without a session or a database lookup, but it cannot be taken back once issued. The usual answer is a short-lived access token paired with a long-lived refresh token that the server can revoke. This page signs and verifies tokens with the JWT support built into Spring Security, then builds login, refresh, rotation and key rotation, and runs each step.

Contents

Why access tokens come with refresh tokens

A JSON Web Token (JWT) is a small JSON document, the claims, with a signature. Any server holding the key can check the signature and read the claims, such as the user name and an expiry time, without asking a database or another service. That makes JWTs fast and easy to scale, and it is also their weakness: a valid token stays valid until it expires, even after the user logs out or is blocked.

The standard way out is to issue two tokens with different jobs:

Access tokens and refresh tokens
Access tokenRefresh token
FormatA signed JWTA random string with no meaning of its own
LifetimeMinutes, for example 5 to 15Days or weeks
Sent toEvery API call, in Authorization: Bearer ...Only the refresh endpoint
Checked bySignature and expiry, with no database lookupA lookup in the server's token table
Can be revokedNo, only waited outYes, by deleting or flagging the row

The access token's short life limits the damage of a stolen token, and the refresh token lets the client get a new one without asking for the password again. Because every refresh goes through a database row, logging out, changing a password or blocking a user takes effect within one access token lifetime.

Spring Security 7 has JWT support built in, so the JJWT library that older tutorials add is not needed. spring-boot-starter-security-oauth2-resource-server brings spring-security-oauth2-jose, which wraps the Nimbus JOSE + JWT library, here version 10.9.1. It provides JwtEncoder to create tokens, JwtDecoder to verify them, and oauth2ResourceServer().jwt() to check bearer tokens on every request. The same pieces are used when tokens come from an external identity provider, as the OAuth2 resource server page shows.

What a JWT contains, and what the signature protects

A token is easiest to understand taken apart. This program signs one with HS256, decodes its three parts, then tries two classic forgeries: editing the payload, and removing the signature:

Java
import java.nio.charset.StandardCharsets;
import java.time.Instant;
import java.util.Base64;
import java.util.List;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.springframework.security.oauth2.jose.jws.MacAlgorithm;
import org.springframework.security.oauth2.jwt.JwsHeader;
import org.springframework.security.oauth2.jwt.Jwt;
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.JwtEncoderParameters;
import org.springframework.security.oauth2.jwt.JwtException;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;

public class JwtAnatomy {

    static String decodePart(String part) {
        return new String(Base64.getUrlDecoder().decode(part), StandardCharsets.UTF_8);
    }

    public static void main(String[] args) {
        // 32 bytes = 256 bits, the minimum for HS256. Load it from a secret store in real code.
        SecretKey key = new SecretKeySpec(
                "a-32-byte-secret-for-hs256-demo!".getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        JwtEncoder encoder = NimbusJwtEncoder.withSecretKey(key).build();
        JwtDecoder decoder = NimbusJwtDecoder.withSecretKey(key).build();

        JwtClaimsSet claims = JwtClaimsSet.builder()
                .issuer("https://auth.example.com")
                .subject("ann")
                .issuedAt(Instant.parse("2026-01-01T10:00:00Z"))
                .expiresAt(Instant.parse("2099-01-01T10:15:00Z"))
                .claim("scope", List.of("orders.read", "orders.write"))
                .build();
        String token = encoder.encode(JwtEncoderParameters.from(
                JwsHeader.with(MacAlgorithm.HS256).build(), claims)).getTokenValue();

        String[] parts = token.split("\\.");
        System.out.println("Token: " + token.length() + " chars in " + parts.length + " parts");
        System.out.println("  header   : " + decodePart(parts[0]));
        System.out.println("  payload  : " + decodePart(parts[1]));
        System.out.println("  signature: " + parts[2].length() + " chars of base64url");

        Jwt jwt = decoder.decode(token);
        System.out.println("Decoded and verified: sub = " + jwt.getSubject()
                + ", scope = " + jwt.getClaimAsStringList("scope"));

        String forgedPayload = Base64.getUrlEncoder().withoutPadding().encodeToString(
                decodePart(parts[1]).replace("\"ann\"", "\"admin\"")
                        .getBytes(StandardCharsets.UTF_8));
        String forged = parts[0] + "." + forgedPayload + "." + parts[2];
        System.out.println("Payload edited to sub = admin, old signature kept:");
        try {
            decoder.decode(forged);
        } catch (JwtException e) {
            System.out.println("  " + e.getClass().getSimpleName() + ": " + e.getMessage());
        }

        String unsigned = Base64.getUrlEncoder().withoutPadding().encodeToString(
                "{\"alg\":\"none\"}".getBytes(StandardCharsets.UTF_8)) + "." + forgedPayload + ".";
        System.out.println("Token with alg = none and no signature:");
        try {
            decoder.decode(unsigned);
        } catch (JwtException e) {
            System.out.println("  " + e.getClass().getSimpleName() + ": " + e.getMessage());
        }
    }
}
Output
Token: 294 chars in 3 parts
  header   : {"kid":"x-IahtycEUJ_KqDpUHkvln_k5l9qaZU-C2Enxq3Xdh4","alg":"HS256"}
  payload  : {"iss":"https://auth.example.com","sub":"ann","exp":4070945700,"iat":1767261600,"scope":["orders.read","orders.write"]}
  signature: 43 chars of base64url
Decoded and verified: sub = ann, scope = [orders.read, orders.write]
Payload edited to sub = admin, old signature kept:
  BadJwtException: An error occurred while attempting to decode the Jwt: Signed JWT rejected: Invalid signature
Token with alg = none and no signature:
  BadJwtException: Unsupported algorithm of none
  • The token is 294 characters in 3 parts separated by dots: header, payload and signature, each base64url-encoded.
  • The header names the algorithm, HS256, and a key id. NimbusJwtEncoder.withSecretKey computed the kid from the key itself, so the same key always gives the same id.
  • The payload is plain JSON: iss, sub, exp and iat as seconds since 1970, and the custom scope list. Anyone who has the token can read it, so never put secrets or personal data in claims.
  • Changing sub to admin and keeping the old signature failed with Invalid signature: the signature covers the header and payload, and only the key holder can produce a new one.
  • A token with "alg":"none" and an empty signature failed with Unsupported algorithm of none. Some early JWT libraries accepted such tokens, which let anyone forge them; the decoder here accepts only the algorithm of its key.

HS256 uses one shared secret for signing and verifying, so every service that verifies tokens could also create them. The secret must be at least 256 bits, and random: a short or guessable one can be brute-forced offline from a single token. When more than one service verifies tokens, use RSA or EC keys instead, as the key rotation section shows.

Expiry, clock skew and the issuer

A decoder checks more than the signature. By default it rejects tokens whose exp has passed or whose nbf (not before) is still in the future. This program checks one 15-minute token at three moments with a fixed clock, then with a decoder that expects a different issuer:

Java
import java.nio.charset.StandardCharsets;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.springframework.security.oauth2.core.DelegatingOAuth2TokenValidator;
import org.springframework.security.oauth2.jose.jws.MacAlgorithm;
import org.springframework.security.oauth2.jwt.JwsHeader;
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.JwtEncoderParameters;
import org.springframework.security.oauth2.jwt.JwtException;
import org.springframework.security.oauth2.jwt.JwtIssuerValidator;
import org.springframework.security.oauth2.jwt.JwtTimestampValidator;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;

public class ExpiryRules {

    static final Instant ISSUED = Instant.parse("2026-03-01T09:00:00Z");

    public static void main(String[] args) {
        SecretKey key = new SecretKeySpec(
                "a-32-byte-secret-for-hs256-demo!".getBytes(StandardCharsets.UTF_8), "HmacSHA256");
        JwtEncoder encoder = NimbusJwtEncoder.withSecretKey(key).build();
        String token = encoder.encode(JwtEncoderParameters.from(
                JwsHeader.with(MacAlgorithm.HS256).build(),
                JwtClaimsSet.builder().issuer("https://auth.example.com").subject("ann")
                        .issuedAt(ISSUED).expiresAt(ISSUED.plus(Duration.ofMinutes(15)))
                        .build())).getTokenValue();
        System.out.println("Token issued 09:00:00, expires 09:15:00");

        for (String time : new String[] {"09:10:00", "09:15:30", "09:16:30"}) {
            Instant now = Instant.parse("2026-03-01T" + time + "Z");
            JwtTimestampValidator timestamps = new JwtTimestampValidator();   // 60 s skew
            timestamps.setClock(Clock.fixed(now, ZoneOffset.UTC));
            NimbusJwtDecoder decoder = NimbusJwtDecoder.withSecretKey(key).build();
            decoder.setJwtValidator(new DelegatingOAuth2TokenValidator<>(timestamps,
                    new JwtIssuerValidator("https://auth.example.com")));
            try {
                decoder.decode(token);
                System.out.println("  checked at " + time + ": accepted");
            } catch (JwtException e) {
                System.out.println("  checked at " + time + ": " + e.getMessage());
            }
        }

        JwtTimestampValidator timestamps = new JwtTimestampValidator();
        timestamps.setClock(Clock.fixed(ISSUED.plusSeconds(60), ZoneOffset.UTC));
        NimbusJwtDecoder strict = NimbusJwtDecoder.withSecretKey(key).build();
        strict.setJwtValidator(new DelegatingOAuth2TokenValidator<>(timestamps,
                new JwtIssuerValidator("https://login.other.com")));
        try {
            strict.decode(token);
        } catch (JwtException e) {
            System.out.println("Decoder expecting issuer https://login.other.com: "
                    + e.getMessage());
        }
    }
}
Output
Token issued 09:00:00, expires 09:15:00
  checked at 09:10:00: accepted
  checked at 09:15:30: accepted
  checked at 09:16:30: An error occurred while attempting to decode the Jwt: Jwt expired at 2026-03-01T09:15:00Z
Decoder expecting issuer https://login.other.com: An error occurred while attempting to decode the Jwt: The iss claim is not valid
  • At 09:10:00, inside its lifetime, the token was accepted.
  • At 09:15:30, 30 seconds after exp, it was still accepted. JwtTimestampValidator allows 60 seconds of clock skew by default, because the server that issued the token and the one that checks it rarely agree to the second.
  • At 09:16:30, 90 seconds after exp, it failed with Jwt expired at 2026-03-01T09:15:00Z.
  • A decoder that expects the issuer https://login.other.com rejected the token with The iss claim is not valid, although the signature was fine.

setJwtValidator replaces the default validators, which is why this program adds JwtTimestampValidator back explicitly. Forgetting that removes the expiry check entirely. JwtValidators.createDefaultWithIssuer(...) returns the defaults plus an issuer check, and createDefaultWithValidators(...) adds your own, such as an audience check, without losing the timestamps.

Login, protected calls and refresh, end to end

This Spring Boot application has a login endpoint that returns both tokens, an API protected by oauth2ResourceServer().jwt(), and a refresh endpoint. The client calls them in the order a real one would, and also tries the failure cases:

Java
package demo.jwt.refresh;

import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;
import java.time.Duration;
import java.time.Instant;
import java.util.Base64;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.ProviderManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.authentication.dao.DaoAuthenticationProvider;
import org.springframework.security.config.Customizer;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.oauth2.jose.jws.MacAlgorithm;
import org.springframework.security.oauth2.jwt.JwsHeader;
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtEncoder;
import org.springframework.security.oauth2.jwt.JwtEncoderParameters;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;
import org.springframework.security.provisioning.InMemoryUserDetailsManager;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

public class JwtRefreshApp {

    static final SecretKey KEY = new SecretKeySpec(
            "a-32-byte-secret-for-hs256-demo!".getBytes(StandardCharsets.UTF_8), "HmacSHA256");

    record Login(String username, String password) {
    }

    record Refresh(String refreshToken) {
    }

    @RestController
    static class AuthController {
        private final AuthenticationManager authenticationManager;
        private final JwtEncoder encoder;
        private final Map<String, String> refreshTokens = new ConcurrentHashMap<>();
        private final SecureRandom random = new SecureRandom();

        AuthController(AuthenticationManager authenticationManager, JwtEncoder encoder) {
            this.authenticationManager = authenticationManager;
            this.encoder = encoder;
        }

        @PostMapping("/auth/login")
        ResponseEntity<Map<String, Object>> login(@RequestBody Login login) {
            try {
                Authentication user = authenticationManager.authenticate(
                        UsernamePasswordAuthenticationToken.unauthenticated(
                                login.username(), login.password()));
                return ResponseEntity.ok(tokens(user.getName()));
            } catch (AuthenticationException e) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
            }
        }

        @PostMapping("/auth/refresh")
        ResponseEntity<Map<String, Object>> refresh(@RequestBody Refresh request) {
            String user = refreshTokens.remove(request.refreshToken());   // one use only
            if (user == null) {
                return ResponseEntity.status(HttpStatus.UNAUTHORIZED).build();
            }
            return ResponseEntity.ok(tokens(user));
        }

        private Map<String, Object> tokens(String user) {
            Instant now = Instant.now();
            JwtClaimsSet claims = JwtClaimsSet.builder()
                    .issuer("https://api.example.com").subject(user)
                    .issuedAt(now).expiresAt(now.plus(Duration.ofMinutes(5)))
                    .claim("scope", "orders.read")
                    .build();
            String access = encoder.encode(JwtEncoderParameters.from(
                    JwsHeader.with(MacAlgorithm.HS256).build(), claims)).getTokenValue();
            byte[] bytes = new byte[32];
            random.nextBytes(bytes);
            String refresh = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
            refreshTokens.put(refresh, user);
            return Map.of("access_token", access, "refresh_token", refresh,
                    "token_type", "Bearer", "expires_in", 300);
        }
    }

    @RestController
    static class ApiController {
        @GetMapping("/api/me")
        String me(Authentication auth) {
            return auth.getName() + " " + auth.getAuthorities().stream()
                    .map(GrantedAuthority::getAuthority)
                    .filter(a -> a.startsWith("SCOPE_")).toList();
        }
    }

    @Configuration
    @EnableAutoConfiguration
    @Import({AuthController.class, ApiController.class})
    static class App {
        @Bean
        SecurityFilterChain security(HttpSecurity http) throws Exception {
            http.authorizeHttpRequests(auth -> auth
                            .requestMatchers("/auth/**", "/error").permitAll()
                            .anyRequest().authenticated())
                    .oauth2ResourceServer(rs -> rs.jwt(Customizer.withDefaults()))
                    .sessionManagement(s -> s.sessionCreationPolicy(
                            SessionCreationPolicy.STATELESS))
                    .csrf(csrf -> csrf.disable());
            return http.build();
        }

        @Bean
        JwtEncoder jwtEncoder() {
            return NimbusJwtEncoder.withSecretKey(KEY).build();
        }

        @Bean
        JwtDecoder jwtDecoder() {
            return NimbusJwtDecoder.withSecretKey(KEY).build();
        }

        @Bean
        UserDetailsService users() {
            return new InMemoryUserDetailsManager(
                    User.withUsername("ann").password("{noop}pw").roles("USER").build());
        }

        @Bean
        AuthenticationManager authenticationManager(UserDetailsService users) {
            return new ProviderManager(new DaoAuthenticationProvider(users));
        }
    }

    static final HttpClient HTTP = HttpClient.newHttpClient();
    static String base;

    static HttpResponse<String> post(String path, String json) throws Exception {
        return HTTP.send(HttpRequest.newBuilder(URI.create(base + path))
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(json)).build(),
                HttpResponse.BodyHandlers.ofString());
    }

    static HttpResponse<String> get(String path, String accessToken) throws Exception {
        HttpRequest.Builder request = HttpRequest.newBuilder(URI.create(base + path));
        if (accessToken != null) {
            request.header("Authorization", "Bearer " + accessToken);
        }
        return HTTP.send(request.build(), HttpResponse.BodyHandlers.ofString());
    }

    static String field(String json, String name) {
        Matcher m = Pattern.compile("\"" + name + "\":\"?([^\",}]+)").matcher(json);
        return m.find() ? m.group(1) : null;
    }

    static void describe(HttpResponse<String> r) {
        if (r.statusCode() != 200) {
            System.out.println("  " + r.statusCode() + r.headers().firstValue("WWW-Authenticate")
                    .map(h -> ", WWW-Authenticate: " + h.replace(base, "http://localhost:PORT"))
                    .orElse(""));
        } else if (r.body().startsWith("{")) {
            System.out.println("  200, access_token " + field(r.body(), "access_token").length()
                    + " chars, refresh_token " + field(r.body(), "refresh_token").length()
                    + " chars, expires_in " + field(r.body(), "expires_in"));
        } else {
            System.out.println("  200 " + r.body());
        }
    }

    public static void main(String[] args) throws Exception {
        SpringApplication app = new SpringApplication(App.class);
        app.setDefaultProperties(Map.of("server.port", "0", "spring.main.banner-mode", "off",
                "logging.level.root", "WARN"));
        try (ConfigurableApplicationContext context = app.run()) {
            base = "http://localhost:" + context.getEnvironment().getProperty("local.server.port");

            System.out.println("POST /auth/login with a wrong password:");
            describe(post("/auth/login", "{\"username\":\"ann\",\"password\":\"nope\"}"));
            System.out.println("POST /auth/login:");
            HttpResponse<String> login = post("/auth/login",
                    "{\"username\":\"ann\",\"password\":\"pw\"}");
            describe(login);
            String access1 = field(login.body(), "access_token");
            String refresh1 = field(login.body(), "refresh_token");

            System.out.println("GET /api/me with the access token:");
            describe(get("/api/me", access1));
            System.out.println("GET /api/me with no token:");
            describe(get("/api/me", null));
            System.out.println("GET /api/me with a damaged token:");
            describe(get("/api/me", access1.substring(0, access1.length() - 2) + "xx"));

            System.out.println("POST /auth/refresh with the refresh token:");
            HttpResponse<String> refreshed = post("/auth/refresh",
                    "{\"refreshToken\":\"" + refresh1 + "\"}");
            describe(refreshed);
            System.out.println("POST /auth/refresh with the same refresh token again:");
            describe(post("/auth/refresh", "{\"refreshToken\":\"" + refresh1 + "\"}"));
            System.out.println("GET /api/me with the first access token, after the refresh:");
            describe(get("/api/me", access1));
        }
    }
}
Output
POST /auth/login with a wrong password:
  401
POST /auth/login:
  200, access_token 270 chars, refresh_token 43 chars, expires_in 300
GET /api/me with the access token:
  200 ann [SCOPE_orders.read]
GET /api/me with no token:
  401, WWW-Authenticate: Bearer resource_metadata="http://localhost:PORT/.well-known/oauth-protected-resource"
GET /api/me with a damaged token:
  401, WWW-Authenticate: Bearer error="invalid_token", error_description="An error occurred while attempting to decode the Jwt: Signed JWT rejected: Invalid signature", error_uri="https://tools.ietf.org/html/rfc6750#section-3.1", resource_metadata="http://localhost:PORT/.well-known/oauth-protected-resource"
POST /auth/refresh with the refresh token:
  200, access_token 270 chars, refresh_token 43 chars, expires_in 300
POST /auth/refresh with the same refresh token again:
  401
GET /api/me with the first access token, after the refresh:
  200 ann [SCOPE_orders.read]
  • A wrong password got 401 from the login endpoint, which uses the same AuthenticationManager as any other Spring Security login.
  • A correct login returned a 270-character access token, a 43-character refresh token (32 random bytes, base64url) and expires_in 300, the access token's lifetime in seconds.
  • With the access token, /api/me returned ann [SCOPE_orders.read]. The resource server turned the scope claim into authorities with the prefix SCOPE_, so rules can use hasAuthority("SCOPE_orders.read").
  • With no token, the response was 401 with WWW-Authenticate: Bearer. With a damaged token, the header also carried error="invalid_token" and the reason, following RFC 6750. Spring Security 7 also adds resource_metadata, the address of the resource's metadata document from RFC 9728; the program prints PORT in place of the random port.
  • The refresh token bought a new pair. Sent a second time, the same refresh token got 401, because the endpoint deletes it on use.
  • The first access token still worked after the refresh. Nothing on the server tracks access tokens, so it stays valid until its exp, five minutes after login.

The refresh endpoint here keeps tokens in a map to stay short; the next section shows what a production version stores. Note what the API itself needs: only a JwtDecoder bean and one line of configuration. Spring Boot can build the decoder from properties instead, with spring.security.oauth2.resourceserver.jwt.public-key-location for a key file or jwk-set-uri for a key set served over HTTP.

Refresh token rotation and reuse detection

A refresh token lives for weeks, so it is the more valuable token to steal. Rotation limits that: every refresh returns a new refresh token and retires the old one. If a retired token is ever presented again, either the client or an attacker has a copy, and the server cannot tell which, so it revokes the whole chain. This program walks through a theft:

Java
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.time.Clock;
import java.time.Duration;
import java.time.Instant;
import java.time.ZoneOffset;
import java.util.Base64;
import java.util.HashMap;
import java.util.HexFormat;
import java.util.Map;
import java.util.Optional;
import java.util.UUID;

public class RefreshRotation {

    /** One row of a refresh_token table. Only the hash of the token is stored. */
    static final class StoredToken {
        final String user;
        final String family;
        final Instant expiresAt;
        boolean used;
        boolean revoked;

        StoredToken(String user, String family, Instant expiresAt) {
            this.user = user;
            this.family = family;
            this.expiresAt = expiresAt;
        }
    }

    static class RefreshTokenService {
        private final Map<String, StoredToken> byHash = new HashMap<>();
        private final SecureRandom random = new SecureRandom();
        private final Duration lifetime;
        Clock clock;

        RefreshTokenService(Duration lifetime, Clock clock) {
            this.lifetime = lifetime;
            this.clock = clock;
        }

        String issue(String user) {
            return issue(user, UUID.randomUUID().toString());
        }

        private String issue(String user, String family) {
            byte[] bytes = new byte[32];
            random.nextBytes(bytes);
            String token = Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
            byHash.put(sha256(token),
                    new StoredToken(user, family, clock.instant().plus(lifetime)));
            return token;
        }

        /** Exchanges a refresh token for a new one; the old one can never be used again. */
        Optional<String> rotate(String token) {
            StoredToken stored = byHash.get(sha256(token));
            if (stored == null || stored.revoked) {
                System.out.println("    rejected: unknown or revoked");
                return Optional.empty();
            }
            if (stored.used) {
                revokeFamily(stored.family);
                System.out.println("    rejected: REUSE of a rotated token, family revoked");
                return Optional.empty();
            }
            if (clock.instant().isAfter(stored.expiresAt)) {
                System.out.println("    rejected: expired");
                return Optional.empty();
            }
            stored.used = true;
            return Optional.of(issue(stored.user, stored.family));
        }

        void revokeFamily(String family) {
            byHash.values().stream().filter(t -> t.family.equals(family))
                    .forEach(t -> t.revoked = true);
        }

        int rows() {
            return byHash.size();
        }

        static String sha256(String token) {
            try {
                return HexFormat.of().formatHex(MessageDigest.getInstance("SHA-256")
                        .digest(token.getBytes(StandardCharsets.UTF_8)));
            } catch (NoSuchAlgorithmException e) {
                throw new IllegalStateException(e);
            }
        }
    }

    static String step(RefreshTokenService service, String label, String token) {
        System.out.println(label);
        Optional<String> next = service.rotate(token);
        next.ifPresent(t -> System.out.println("    ok: new refresh token, " + t.length()
                + " chars"));
        return next.orElse(null);
    }

    public static void main(String[] args) {
        Instant start = Instant.parse("2026-03-01T09:00:00Z");
        RefreshTokenService service = new RefreshTokenService(Duration.ofDays(14),
                Clock.fixed(start, ZoneOffset.UTC));

        String r1 = service.issue("ann");
        System.out.println("Login: refresh token r1 issued, " + r1.length() + " chars");
        String r2 = step(service, "Client refreshes with r1:", r1);
        String r3 = step(service, "Client refreshes with r2:", r2);
        step(service, "Attacker replays stolen r1:", r1);
        step(service, "Client refreshes with r3, its latest token:", r3);
        System.out.println("Rows stored: " + service.rows() + ", none holds a usable token");

        String fresh = service.issue("ann");
        service.clock = Clock.fixed(start.plus(Duration.ofDays(15)), ZoneOffset.UTC);
        step(service, "New login, then a refresh 15 days later:", fresh);
    }
}
Output
Login: refresh token r1 issued, 43 chars
Client refreshes with r1:
    ok: new refresh token, 43 chars
Client refreshes with r2:
    ok: new refresh token, 43 chars
Attacker replays stolen r1:
    rejected: REUSE of a rotated token, family revoked
Client refreshes with r3, its latest token:
    rejected: unknown or revoked
Rows stored: 3, none holds a usable token
New login, then a refresh 15 days later:
    rejected: expired
  • The login issued r1, and two normal refreshes exchanged it for r2, then r3. Each old token was marked used, not deleted, so that a replay can be recognised.
  • The attacker replayed the stolen r1. The service found it marked used, treated that as theft, and revoked every token of the same family, the chain that started at that login.
  • The real client's next refresh, with its latest token r3, was rejected too. The user has to log in again, which also locks the attacker out.
  • A refresh token from a new login, presented 15 days later, was rejected as expired, because refresh tokens here live 14 days.

Several design choices in this service matter in production:

  • Store only a hash: the table holds SHA-256 of each token. Someone who reads the table cannot use the values, and because the tokens are long and random, a fast hash is enough; a slow password hash is not needed.
  • Keep a family id: one id per login lets you revoke one device's chain on reuse, or all of a user's families on a password change.
  • Use a transaction: two parallel refreshes with the same token must not both succeed. Mark the row used with a conditional update, such as UPDATE ... SET used = TRUE WHERE hash = ? AND used = FALSE, and treat zero updated rows as reuse.
  • Allow a short grace period, if needed: a mobile client that sends a refresh and loses the response retries with the old token. Some systems accept a reuse within a few seconds instead of revoking, at some cost in safety.

Signing with RSA keys and rotating them

With RSA or EC keys, only the authentication server holds the private key; resource servers get the public key, usually as a JSON Web Key (JWK) set served at a URL. Keys should be replaced from time to time, and tokens signed with the old key are still in circulation when that happens. This program signs two tokens with two keys and verifies them before and after the old key is retired:

Java
import com.nimbusds.jose.jwk.JWK;
import com.nimbusds.jose.jwk.JWKSet;
import com.nimbusds.jose.jwk.RSAKey;
import com.nimbusds.jose.jwk.source.ImmutableJWKSet;
import java.nio.charset.StandardCharsets;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.interfaces.RSAPrivateKey;
import java.security.interfaces.RSAPublicKey;
import java.time.Instant;
import java.util.Base64;
import java.util.List;
import org.springframework.security.oauth2.jose.jws.SignatureAlgorithm;
import org.springframework.security.oauth2.jwt.JwsHeader;
import org.springframework.security.oauth2.jwt.JwtClaimsSet;
import org.springframework.security.oauth2.jwt.JwtDecoder;
import org.springframework.security.oauth2.jwt.JwtEncoderParameters;
import org.springframework.security.oauth2.jwt.JwtException;
import org.springframework.security.oauth2.jwt.NimbusJwtDecoder;
import org.springframework.security.oauth2.jwt.NimbusJwtEncoder;

public class RsaKeyRotation {

    static RSAKey newKey(String id) throws Exception {
        KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");
        generator.initialize(2048);
        KeyPair pair = generator.generateKeyPair();
        return new RSAKey.Builder((RSAPublicKey) pair.getPublic())
                .privateKey((RSAPrivateKey) pair.getPrivate()).keyID(id).build();
    }

    static String sign(RSAKey key, String subject) {
        NimbusJwtEncoder encoder = new NimbusJwtEncoder(new ImmutableJWKSet<>(new JWKSet(key)));
        return encoder.encode(JwtEncoderParameters.from(
                JwsHeader.with(SignatureAlgorithm.RS256).keyId(key.getKeyID()).build(),
                JwtClaimsSet.builder().subject(subject)
                        .expiresAt(Instant.parse("2099-01-01T00:00:00Z")).build()))
                .getTokenValue();
    }

    static void verify(String label, JwtDecoder decoder, String token) {
        try {
            System.out.println("  " + label + ": accepted, sub = "
                    + decoder.decode(token).getSubject());
        } catch (JwtException e) {
            System.out.println("  " + label + ": " + e.getMessage());
        }
    }

    public static void main(String[] args) throws Exception {
        RSAKey oldKey = newKey("key-2026-01");
        RSAKey newKey = newKey("key-2026-07");
        String oldToken = sign(oldKey, "ann");
        String newToken = sign(newKey, "bob");

        String header = new String(Base64.getUrlDecoder().decode(oldToken.split("\\.")[0]),
                StandardCharsets.UTF_8);
        System.out.println("Header: " + header + ", token " + oldToken.length() + " chars");

        JWKSet published = new JWKSet(List.of(oldKey.toPublicJWK(), newKey.toPublicJWK()));
        System.out.println("Published JWK set has " + published.getKeys().size()
                + " public keys, private parts included: "
                + published.getKeys().stream().anyMatch(JWK::isPrivate));

        System.out.println("Resource server with both public keys:");
        JwtDecoder both = NimbusJwtDecoder.withJwkSource(new ImmutableJWKSet<>(published)).build();
        verify("token signed with key-2026-01", both, oldToken);
        verify("token signed with key-2026-07", both, newToken);

        System.out.println("After key-2026-01 is retired:");
        JwtDecoder onlyNew = NimbusJwtDecoder.withJwkSource(
                new ImmutableJWKSet<>(new JWKSet(newKey.toPublicJWK()))).build();
        verify("token signed with key-2026-01", onlyNew, oldToken);
        verify("token signed with key-2026-07", onlyNew, newToken);
    }
}
Output
Header: {"kid":"key-2026-01","alg":"RS256"}, token 431 chars
Published JWK set has 2 public keys, private parts included: false
Resource server with both public keys:
  token signed with key-2026-01: accepted, sub = ann
  token signed with key-2026-07: accepted, sub = bob
After key-2026-01 is retired:
  token signed with key-2026-01: An error occurred while attempting to decode the Jwt: Signed JWT rejected: Another algorithm expected, or no matching key(s) found
  token signed with key-2026-07: accepted, sub = bob
  • The header now says RS256 and carries the key id key-2026-01, chosen when the key was built. The token is 431 characters, longer than the HS256 one, because a 2048-bit RSA signature is 256 bytes.
  • The published JWK set holds 2 public keys and no private parts: toPublicJWK() strips them, and publishing a private key by mistake would let anyone sign tokens.
  • A decoder with both keys accepted both tokens. It picked the key for each token by its kid.
  • After key-2026-01 was removed, its token failed with no matching key(s) found, while the other still worked.

The safe order for a rotation follows from this: publish the new public key first, start signing with it once every resource server has fetched the new set, and remove the old key only after the longest-lived token signed with it has expired. With access tokens of a few minutes that wait is short, which is another reason to keep them short. A decoder built with withJwkSetUri refetches the key set when it meets an unknown kid, so resource servers pick up new keys without a restart.

Where to keep tokens in the client

  • Browser, same site as the API: keep the refresh token in an HttpOnly, Secure, SameSite cookie that only the refresh path receives, and the access token in memory. JavaScript cannot read the cookie, so an XSS bug cannot steal it. The refresh endpoint then authenticates with a cookie, so it needs CSRF protection, as the CSRF and CORS page explains.
  • Not localStorage: any script on the page can read it, including one injected through an XSS bug.
  • Mobile apps: the platform's secure storage, such as the iOS Keychain or Android Keystore.
  • Server-side web apps: often no tokens in the browser at all; the server keeps them and the browser holds a session cookie.

Logout deletes the refresh token's row and the client's copies. The access token cannot be recalled; if a few minutes of continued access after logout is not acceptable, keep a small deny list of revoked token ids (the jti claim) that the API checks until those tokens expire, accepting that this gives up part of the stateless design.

Choosing a token setup

Common situations and the setup that fits
SituationSetup
One application that issues and checks its own tokensHS256 with a 256-bit random secret, short access tokens, rotating refresh tokens
Several services check tokens from one login serviceRS256 or ES256, public keys published as a JWK set, jwk-set-uri on each service
Users log in through Keycloak, Okta, Entra ID or similarDo not issue tokens yourself: use the provider's tokens with OAuth2 resource server support
Browser single-page applicationRefresh token in an HttpOnly cookie, access token in memory, CSRF protection on the refresh endpoint
Immediate logout or blocking is requiredVery short access tokens, or opaque tokens checked on each call
A server-rendered websiteSessions instead of JWTs: see Spring Security in Spring Boot

A JWT is a cache of a login decision, signed so that it cannot be altered. Keep it short-lived, keep its claims small, and put everything that must be revocable behind the refresh token. To read the user's identity from the token in controllers and services, see method security and the authentication options on the custom authentication page.