Skip to content
Seamless Token Refresh: Backend Auto-Renewal vs Frontend Dual-Token Strategies

Seamless Token Refresh: Backend Auto-Renewal vs Frontend Dual-Token Strategies

This article explains why tokens expire causing sudden logouts, then details two seamless refresh approaches: backend-driven automatic token renewal via response headers and frontend dual-token (access/refresh) pattern with code examples using JWT, Hutool, and FastJSON.

Java Architect Handbook
Java Architect Handbook
Java Architect Handbook

Why Seamless Token Refresh Is Needed

When a user performs actions on a page, the app may suddenly redirect to login because the token expired. The system uses Redis to cache user IDs and token info; expiration invalidates the identity.

Backend Automatic Token Refresh

The backend checks token expiry during validation. If the token is about to expire (e.g., remaining time less than a threshold), it generates a new token and places it in the response header. The frontend intercepts the response, compares the new token with the stored one, and updates local storage if different.

Dependencies

<dependency>
  <groupId>cn.hutool</groupId>
  <artifactId>hutool-all</artifactId>
  <version>5.5.1</version>
</dependency>
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>fastjson</artifactId>
  <version>1.2.33</version>
</dependency>
<dependency>
  <groupId>io.jsonwebtoken</groupId>
  <artifactId>jjwt</artifactId>
  <version>0.9.1</version>
</dependency>

JWT Utility Class

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.JwtBuilder;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Base64;
import java.util.Date;
import java.util.UUID;

public class JwtUtil {
  public static final Long JWT_TTL = 60 * 60 * 1000 * 24; // 24 hours
  public static final String JWT_KEY = "qx";

  public static String getUUID() {
    return UUID.randomUUID().toString().replaceAll("-", "");
  }

  public static String createJWT(String subject) {
    return createJWT(subject, null);
  }

  public static String createJWT(String subject, Long ttlMillis) {
    return createJWT(getUUID(), subject, ttlMillis);
  }

  public static String createJWT(String id, String subject, Long ttlMillis) {
    JwtBuilder builder = getJwtBuilder(subject, ttlMillis, id);
    return builder.compact();
  }

  private static JwtBuilder getJwtBuilder(String subject, Long ttlMillis, String uuid) {
    SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
    SecretKey secretKey = generalKey();
    long nowMillis = System.currentTimeMillis();
    Date now = new Date(nowMillis);
    if (ttlMillis == null) ttlMillis = JWT_TTL;
    long expMillis = nowMillis + ttlMillis;
    Date expDate = new Date(expMillis);
    return Jwts.builder()
      .setId(uuid)
      .setSubject(subject)
      .setIssuer("sg")
      .setIssuedAt(now)
      .signWith(signatureAlgorithm, secretKey)
      .setExpiration(expDate);
  }

  public static SecretKey generalKey() {
    byte[] encodedKey = Base64.getDecoder().decode(JWT_KEY);
    return new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
  }

  public static Claims parseJWT(String jwt) throws Exception {
    SecretKey secretKey = generalKey();
    return Jwts.parser()
      .setSigningKey(secretKey)
      .parseClaimsJws(jwt)
      .getBody();
  }
}

Unit Test & Expiration Calculation

@Test
void test() throws Exception {
  String token = JwtUtil.createJWT("1735209949551763457");
  System.out.println("Token: " + token);
  Date tokenExpirationDate = getTokenExpirationDate(token);
  System.out.println(tokenExpirationDate);
  long exp = tokenExpirationDate.getTime();
  long cur = System.currentTimeMillis();
  System.out.println(exp - cur); // ~86398965 ms
}

public static Date getTokenExpirationDate(String token) {
  try {
    SecretKey secretKey = generalKey();
    Claims claims = Jwts.parser()
      .setSigningKey(secretKey)
      .parseClaimsJws(token)
      .getBody();
    return claims.getExpiration();
  } catch (ExpiredJwtException | SignatureException e) {
    throw new RuntimeException("Invalid token", e);
  }
}

The test shows expiration milliseconds (exp) minus current milliseconds (cur) ≈ 86,398,965 ms, close to one day (86,400,000 ms). During token validation, if (expiration - now) < threshold, the backend creates a new token from the old token's claims and returns it in the response header for the frontend to store.

Frontend Token Renewal (Dual-Token Pattern)

The frontend holds two tokens: access-token (AT) and refresh-token (RT). AT is short-lived (e.g., 30 min) and sent with every request; RT is long-lived (e.g., 7 days) and used only to obtain a new AT via a dedicated refresh endpoint.

AT exposed frequently → short expiry reduces hijack risk.

RT exposed only during refresh → longer expiry improves convenience.

This mirrors standard security practice (like HTTPS over HTTP). When AT nears expiry, the frontend uses RT to request a new AT without user interaction.

Open Questions & Considerations

Scenario: User spends long time filling a form without sending requests. On submit, backend returns 401 because token expired. Backend auto-refresh requires a request to trigger; frontend dual-token also fails if both AT and RT expired.

Proposed Solutions

Backend-only: On 401, frontend saves form data to localStorage, redirects to login, then restores form after login.

Frontend dual-token: Monitor RT expiry; proactively refresh RT before it expires (periodic background request). Also implement a draft-saving feature (like auto-save) to preserve form state.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaSpring BootsecurityauthenticationJWTaccess tokenrefresh tokentoken refresh
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.