JWT and refresh token rotation

You can issue a verifiable 15-minute access token and rotate a one-use refresh token, which signup, login and refresh need to return credentials safely.

Learning outcomes

  • Explain JWT structure and how HS256 signatures protect access-token claims from modification.
  • Issue 15-minute access tokens with a verifiable signature and the required expiration claims.
  • Distinguish stateless access tokens from opaque refresh tokens stored in Redis.
  • Explain atomic refresh-token rotation, replay rejection and the difference between token rejection and token-family revocation.
Prerequisite conceptscrypto/rand

After signup or login, the API needs to recognise a user on subsequent requests without asking for their password every time. The Week 4 app needs a credential for protected requests such as GET /v1/me, and another credential it can exchange when the first expires.

You will use two different credentials. A JSON Web Token (JWT) carries signed claims about the caller. An opaque refresh token lets the client obtain a replacement pair without asking the user to log in again.

Access and refresh credentials

The access token authenticates API requests. The refresh token obtains a replacement access token after the current one expires.

These credentials have different responsibilities.

PropertyAccess tokenRefresh token
FormatSigned JWTOpaque random string
Lifetime15 minutes30 days in this implementation
StorageClientRedis, associated with user ID
ValidationSignature and claimsRedis lookup
PurposeAuthenticate API requestsObtain a replacement token pair

The access token is stateless. The API can verify it using its signing secret without looking up a Redis entry on every request.

The refresh token is stateful. Redis records which user owns it and whether it remains usable.

This separation limits how long a stolen access token remains useful while allowing the client to maintain a login session.

JWT structure

A JWT consists of three Base64url-encoded sections separated by periods:

header.payload.signature

Each section has a different responsibility.

The header identifies the token type and signing algorithm.

For this project, the decoded header looks like:

json
{
  "alg": "HS256",
  "typ": "JWT"
}

HS256 means HMAC using SHA-256. It uses a shared secret to generate and verify the signature.

The header is part of the token itself. It does not prove that the token is trustworthy.

Payload

The payload contains claims. Claims are statements about the user or the token's validity period.

A decoded payload for a customer account could look like:

json
{
  "sub": "123",
  "role": "customer",
  "iat": 1793433600,
  "exp": 1793434500
}

The important claims are:

ClaimMeaning
subSubject, identifying the user
iatTime when the token was issued
expTime when the token expires
roleApplication-specific account role

The sub claim contains the user's database ID as a string. The role claim contains the account role, such as customer, restaurant or rider.

The JWT library provides standard registered claims through jwt.RegisteredClaims. You can add application-specific claims alongside them.

Signature

The signature protects the token against modification.

Conceptually, HS256 uses the encoded header, encoded payload and shared secret to calculate a signature.

The encoded header and payload are combined and signed using HMAC-SHA256. The resulting value is the JWT signature.

When the API receives a token, it calculates the expected signature using its own secret and compares it with the supplied signature.

Changing the payload from customer to restaurant changes the signed content. The original signature will no longer validate.

Base64url encoding and confidentiality

Base64url encoding does not encrypt the JWT payload. Anyone who possesses the token can decode its header and payload without knowing the signing secret.

The signature protects integrity, not confidentiality.

HS256 signing

Your authentication service signs access tokens with JWT_SECRET. The API uses the same secret to verify them.

HS256 is a symmetric signing algorithm. Anyone who possesses the shared secret can both issue and verify valid tokens.

The project requires JWT_SECRET to contain at least 32 bytes. Load it from the environment rather than committing it to source control.

For this project, the token uses a 15-minute lifetime.

go
claims := jwt.RegisteredClaims{
    Subject:   strconv.FormatInt(userID, 10),
    IssuedAt:  jwt.NewNumericDate(now),
    ExpiresAt: jwt.NewNumericDate(now.Add(15 * time.Minute)),
}

The now value represents the issue time. The expiration is calculated by adding 15 minutes.

The signer creates a JWT using jwt.SigningMethodHS256 and signs it with JWT_SECRET.

A successful signup or login returns a response containing this information:

json
{
  "access_token": "<signed-jwt>",
  "refresh_token": "<opaque-random-token>",
  "token_type": "Bearer",
  "expires_in": 900
}

The expires_in value is measured in seconds. Fifteen minutes equals 900 seconds.

The JWT's exp claim must also represent an expiration about 15 minutes after issuance. Returning expires_in: 900 without setting the corresponding JWT expiration would not enforce the actual lifetime.

Signing algorithm verification

Your API must not blindly trust the algorithm specified in an incoming JWT header.

An attacker could construct a token using an unexpected signing algorithm. Accepting arbitrary algorithms can introduce algorithm-confusion vulnerabilities.

Your parser should accept only HS256.

The jwt/v5 package supports an explicit allowlist:

go
parser := jwt.NewParser(
    jwt.WithValidMethods([]string{"HS256"}),
)

The key function should also check the actual signing method before returning the shared secret.

go
keyFunc := func(token *jwt.Token) (any, error) {
    if token.Method != jwt.SigningMethodHS256 {
        return nil, errors.New("unexpected signing method")
    }
    return secret, nil
}

These checks serve complementary purposes. The allowlist restricts the parser, while the key function refuses an unexpected method at the point where the verification key is selected.

The parser must also validate expiration. A token with a valid signature can still be expired and must be rejected.

In jwt/v5, jwt.WithExpirationRequired() requires an exp claim to be present. jwt.WithIssuedAt() enables validation that the issued-at timestamp is not in the future.

Signing secret management

The environment variable JWT_SECRET supplies the signing secret.

Generate it using cryptographically secure randomness and keep it outside the source repository.

  • Load it from the environment during startup.
  • Require at least 32 bytes.
  • Never commit it to Git.
  • Never print it in application logs.

A missing or weak secret should prevent the authentication service from starting.

Access-token lifetime

The access token is designed for repeated API requests without a Redis lookup on every request.

The API verifies the signature and claims locally. The token identifies the user through sub and carries the account's role.

For this project, the lifetime is 15 minutes.

A shorter lifetime limits how long a stolen access token can be used. However, it also means the client needs a way to obtain replacement credentials without repeatedly asking the user for their password.

There is a trade-off with stateless tokens: deleting a refresh token does not automatically invalidate an access token that has already been issued.

The access token can remain valid until its expiration unless you introduce additional server-side revocation checks. That is why the project uses a short access-token lifetime.

Refresh tokens in Redis

A refresh token is not another JWT. It is an opaque, cryptographically random string.

It contains no readable user ID, role or expiration claim. The server maintains the relationship between the token and its owner in Redis.

The earlier crypto/rand lesson covered the generation of secure random values. For this project, a refresh token contains 32 random bytes.

go
raw := make([]byte, 32)
_, err := rand.Read(raw)
if err != nil {
    return "", err
}

token := hex.EncodeToString(raw)

The resulting representation contains 64 lowercase hexadecimal characters.

32 random bytes contain 256 bits of randomness. Hexadecimal encoding represents those bytes as 64 lowercase hexadecimal characters without changing the amount of randomness.

Hexadecimal encoding makes the token convenient to transmit and store. It does not increase the amount of randomness.

There are 2^256 possible values for a uniformly generated 256-bit token. Guessing such a token by brute force is infeasible.

Do not use math/rand for authentication credentials. It is intended for non-security-sensitive random values. Use crypto/rand instead.

Redis association

Redis stores the association between a refresh token and the corresponding user ID.

The implementation uses this key structure:

Key:   refresh:{token}
Value: user_id
TTL:   30 days

For example:

refresh:a81f...9c20 -> 123

The TTL limits how long the credential remains usable. Once the entry expires, Redis no longer recognises the token.

Unlike an access token, a refresh token can be invalidated by removing its Redis entry.

This makes refresh-token validation stateful. Redis determines whether the supplied credential still exists and identifies its associated user.

Refresh-token rotation

Refresh-token rotation replaces a refresh token every time the client successfully uses it.

Suppose the client receives refresh token A during login. Later, the access token expires and the client exchanges A for a new token pair containing refresh token B.

Token A must stop working after that exchange.

The refresh process has a few important operations:

  1. Consume the submitted refresh token.
  2. Identify its associated user.
  3. Obtain the user's current role from MySQL.
  4. Generate a new access token and refresh token.
  5. Store the replacement refresh token in Redis.
  6. Return the new pair.

The most important operation is consuming the old token.

Atomic consumption with GETDEL

Redis provides the GETDEL command, which retrieves a key's value and deletes the key as one atomic operation.

GETDEL refresh:{token}

The operation returns the stored user ID and removes the original key.

If the key does not exist, Redis returns nil.

This matters when multiple requests attempt to use the same refresh token concurrently.

Consider two requests presenting token A:

  1. Request A executes GETDEL on refresh token A and receives the stored user ID.
  2. Redis deletes token A atomically.
  3. Request B executes GETDEL on token A and receives nil because the key no longer exists.
  4. Request A issues replacement token B.
  5. Request B returns HTTP 401.

Only one request can successfully consume the original key.

If you use separate GET and DEL commands, both requests might read the same value before either deletes the key. Both could then issue replacement credentials.

GETDEL avoids this race at the Redis operation boundary.

The project uses Redis 7, which supports this command.

Rotation lifecycle

The complete sequence looks like this:

The client receives access token and refresh token A. Redis stores A. When the client refreshes, the API atomically consumes A, issues a replacement access token and refresh token B, and stores B. Replaying A returns 401 because its Redis entry no longer exists.The client receives access token and refresh token A. Redis stores A. When the client refreshes, the API atomically consumes A, issues a replacement access token and refresh token B, and stores B. Replaying A returns 401 because its Redis entry no longer exists.

After the first successful refresh, the client must replace both locally stored credentials.

It must not continue using the consumed refresh token.

A successful replacement can itself be used for another refresh. This creates a chain of one-use refresh credentials.

Replay rejection

A replay occurs when someone presents a refresh token that has already been consumed.

For example:

First request:
    Refresh token A
    Returns HTTP 200 with token B

Second request:
    Refresh token A
    Returns HTTP 401
    error: invalid_refresh_token

The second request finds no Redis entry for A.

An unknown token also produces HTTP 401 with invalid_refresh_token. The API does not need to reveal whether the token expired, was already used or was never issued.

The original token and an unknown token are therefore indistinguishable to the client.

Replay rejection and token-family revocation

Rejecting a replay does not necessarily revoke every credential from the same login.

In the current exercise, the original token A is deleted when it is consumed. Replaying A returns 401 invalid_refresh_token. The replacement token B remains valid.

This is replay rejection, not token-family revocation.

The optional W3O1 extension adds reuse detection. It tracks relationships between tokens from the same login and revokes the newest token of that login when a previously rotated token is presented again.

Other logins belonging to the same user remain usable.

That stronger behaviour requires additional server-side state. A simple GETDEL is not enough because consuming a token removes the key that originally associated it with the user.

For W3B1, rejection of a consumed or unknown token is the required behaviour. Do not confuse it with the optional family-revocation extension.

Refresh failure boundaries

MySQL and Redis do not share a transaction. This creates a failure boundary during token issuance.

For example, Redis may successfully consume the old token, but a subsequent operation may fail before the replacement pair reaches the client.

The original token is already gone. The client cannot use it again.

This is a trade-off of one-use rotation. Your API must distinguish an invalid or missing token from an operational failure in Redis or MySQL.

A missing token produces the authentication error. An infrastructure failure should not be misreported as an invalid credential.

Signup, login and refresh

The exercise POST /v1/auth/*: signup, login and refresh connects these concepts.

Signup and login issue the same kind of token pair. The access token is signed using HS256 and expires after 15 minutes. The opaque refresh token is generated from 32 random bytes and stored in Redis with a TTL.

The refresh endpoint consumes the submitted token and issues a replacement pair. The original token must become unusable after successful rotation.

Keep the responsibilities separate as you work through the exercise:

  • JWT signing establishes the integrity of the access token.
  • JWT verification checks the signature and claims.
  • Redis determines whether a refresh token remains usable.
  • Atomic consumption ensures that a refresh token succeeds only once.

W3B2 will use the access-token verification logic in bearer authentication middleware. That middleware will establish the caller's identity before protected handlers run.

Check your understanding

Question 1 of 4

A client decodes an access token and changes its role claim from customer to restaurant. It keeps the original signature. What should the API do?

Pick an answer, then say how sure you are.

References

Everything above is explained on this page; these are where it comes from (golang-jwt/jwt v5, go-redis v9, Redis 7).

Finished Lesson 3.2?