Token Refresh & Rotation
CyberGo JWT uses a two-tier token design: short-lived access tokens authenticate API calls, and long-lived refresh tokens exchange for new access tokens once the old one expires. The design balances security and user experience.
Two-Tier Token Model
| Token Type | Issuance Method | Default TTL | Purpose |
|---|---|---|---|
| Access token | Create | 15 minutes | API authentication, frequent validation |
| Refresh token | CreateRefresh | 7 days | Exchange for new access tokens, infrequent use |
Token type is marked via the token_type claim (access / refresh). The Refresh method rejects access tokens, preventing them from being used to obtain new tokens.
TTL Configuration
cfg := jwt.DefaultConfig()
cfg.SecretKey = "hmac-key-that-has-at-least-32-bytes!"
cfg.AccessTokenTTL = 15 * time.Minute // Access token lifetime
cfg.RefreshTokenTTL = 7 * 24 * time.Hour // Refresh token lifetime (must be > AccessTokenTTL)Constraint
Config.Validate() requires RefreshTokenTTL > AccessTokenTTL, otherwise it returns ErrInvalidConfig.
Basic Refresh Flow
1. Issue Token Pair
package main
import (
"fmt"
"time"
"github.com/cybergodev/jwt"
)
func main() {
cfg := jwt.DefaultConfig()
cfg.SecretKey = "hmac-key-that-has-at-least-32-bytes!"
cfg.AccessTokenTTL = 15 * time.Minute
cfg.RefreshTokenTTL = 7 * 24 * time.Hour
processor, err := jwt.New(cfg)
if err != nil {
panic(err)
}
defer processor.Close()
claims := &jwt.Claims{UserID: "user123", Username: "alice"}
// Access token (short-lived)
accessToken, err := processor.Create(claims)
if err != nil {
panic(err)
}
// Refresh token (long-lived)
refreshToken, err := processor.CreateRefresh(claims)
if err != nil {
panic(err)
}
fmt.Println("Access Token:", accessToken)
fmt.Println("Refresh Token:", refreshToken)
}2. Refresh to Get a New Access Token
When the access token expires, use the refresh token to obtain a new one:
// refreshToken was previously issued via CreateRefresh
newAccessToken, err := processor.Refresh(refreshToken)
if err != nil {
switch {
case errors.Is(err, jwt.ErrTokenExpired):
// Refresh token expired, user needs to re-authenticate
case errors.Is(err, jwt.ErrTokenRevoked):
// Refresh token has been revoked
case errors.Is(err, jwt.ErrTokenTypeMismatch):
// An access token was passed instead of a refresh token
default:
// Other error
}
return
}
fmt.Println("New Access Token:", newAccessToken)Refresh fully validates the refresh token: signature, expiration, issuer, audience, and blacklist status.
Custom Claims Refresh
With a custom Claims type, use RefreshInto to populate the parsed result into the custom struct:
type MyClaims struct {
UserID string `json:"user_id"`
Role string `json:"role"`
Tenant string `json:"tenant"` // Business field with no counterpart in the built-in Claims
jwt.RegisteredClaims
}
func (c *MyClaims) GetRegisteredClaims() *jwt.RegisteredClaims {
return &c.RegisteredClaims
}
func (c *MyClaims) Validate() error {
if c.UserID == "" {
return errors.New("user_id is required")
}
return nil
}// Issue a refresh token with a custom Claims type
refreshToken, err := processor.CreateRefresh(&MyClaims{UserID: "123", Role: "admin"})
// Refresh into the custom struct
result := &MyClaims{}
newToken, err := processor.RefreshInto(refreshToken, result)Custom types must always use RefreshInto, never Refresh. Two constraints apply:
Refreshloses custom fields:Refreshparses the token as the built-inClaimsand rebuilds it, so theTenantfield from the example above does not appear in the new token. OnlyRefreshIntorebuilds the original type.- A refresh token validated as the built-in
ClaimsneedsUserIDorUsername: a custom refresh token that only carriesSubjectmakesRefreshreturninvalid claims: user_id or username is required.RefreshIntoruns the customValidate()and is not subject to this rule.
// ❌ Refresh: custom fields are lost, and UserID/Username is required
if _, err := processor.Refresh(refreshToken); err != nil {
panic(err)
}
// ✅ RefreshInto: custom fields are preserved, validated by MyClaims.Validate()
newToken, err := processor.RefreshInto(refreshToken, &MyClaims{})
if err != nil {
panic(err)
}
fmt.Println("New Token:", newToken)Rotation Strategies
Reuse Mode (Default)
By default, Refresh does not revoke the original refresh token. The original token remains valid until it expires or is explicitly revoked, and can be used multiple times:
// First refresh
token1, err := processor.Refresh(refreshToken)
if err != nil {
panic(err)
}
// The same refreshToken is still valid and can be used again
token2, err := processor.Refresh(refreshToken)
if err != nil {
panic(err)
}Use cases: mobile apps and single-device logins. Users rarely need to re-authenticate, and the refresh token can be reused within its TTL.
One-Time Rotation
For higher-security scenarios, make each refresh token usable only once. Since v1.2.3 the recommended approach is the built-in rotation switch Config.RotateRefreshTokens v1.2.3+:
cfg := jwt.DefaultConfig()
// ...required config such as keys and TTLs
cfg.RotateRefreshTokens = true // one-time use: Refresh revokes the old token before minting the new one
processor, err := jwt.New(cfg)
if err != nil {
panic(err)
}
// Refresh / RefreshInto automatically revoke the old refresh token
// (blacklist its jti) before minting the new access token
newAccessToken, err := processor.Refresh(refreshToken)
if err != nil {
panic(err)
}Fail-Closed Semantics and Concurrency
- Revocation precedes minting: the old token's jti is blacklisted before the new token is minted. If minting then fails (for example the rate limit trips), the old token is already invalid and the subject must re-authenticate. This is a deliberate fail-closed design ensuring an accepted refresh token cannot be replayed afterwards.
- Errors: if revoking the old token fails,
ErrRefreshRotationFailedis returned (wrapping the underlying blacklist store error) and no new token is issued. A refresh token without ajticannot be revoked and returnsErrTokenMissingID. A processor without a configured blacklist returnsErrBlacklistNotConfigured; processors built throughjwt.New()always carry a blacklist, so normal use never hits this. - Concurrency: rotation narrows but does not eliminate the replay window: two concurrent
Refreshcalls can both pass validation before either revocation takes effect. A strict single-use guarantee requires a customBlacklistStoreimplementing atomic check-and-add.
When the configuration cannot be changed, manual Refresh + Revoke is an equivalent alternative:
// Refresh and immediately revoke the old token
newAccessToken, err := processor.Refresh(refreshToken)
if err != nil {
panic(err)
}
// Revoke the old refresh token so it cannot be used again
if err := processor.Revoke(refreshToken); err != nil {
panic(err)
}Note that the manual approach leaves a window: the old token remains usable between a successful Refresh and the Revoke taking effect. A failure of the second step after the first succeeds also needs explicit handling.
Use cases: Web applications, high-security systems. The old token becomes invalid immediately after each refresh, reducing the risk of token leakage.
Strategy Comparison
| Dimension | Reuse Mode | One-Time Rotation |
|---|---|---|
| Security | Lower (leaked tokens can be reused) | Higher (leaked tokens are single-use only) |
| User experience | Better (no frequent re-authentication) | Average (refresh failure requires re-login) |
| Implementation | No extra code | One config switch (RotateRefreshTokens), or calling Revoke manually |
| Blacklist pressure | Low | Higher (each refresh adds an entry) |
Refresh Token Leak Detection
In one-time rotation mode, if an attacker uses a revoked refresh token, Refresh returns ErrTokenRevoked. The application layer can use this to detect token leakage and force re-authentication.
Type Safety
CyberGo JWT distinguishes token types via the token_type claim. Refresh and RefreshInto reject access tokens:
// Attempting to refresh with an access token is rejected
_, err := processor.Refresh(accessToken)
// err wraps ErrTokenTypeMismatch: expected refresh token, got access tokenThis prevents access tokens from being used to obtain new tokens, ensuring type isolation in the two-tier model.
Tokens without a token_type claim (issued by older versions) are accepted for backward compatibility.
Security Notes
- Refresh does not auto-revoke by default: the original refresh token stays valid after
Refresh. For one-time-use semantics, see One-Time Rotation. - Claims are not deeply validated:
Refreshvalidates the standard JWT fields (signature, expiration, issuer, audience, blacklist) and the basic structure (UserIDorUsernamemust be present), but does not re-check field length limits or injection patterns. It trusts that creation-time validation already ran. - Signature consistency: new access tokens use the same signing algorithm and key as the refresh token. Cross-algorithm refresh is not supported.
Next Steps
- Token Blacklist — Revocation mechanism and custom storage backends
- Error Handling — All sentinel error categories and handling
- Configuration — TTL, issuer, audience, and clock skew configuration
- Processor API — Full signatures for
Refresh,RefreshInto,CreateRefresh