JWT and Token Validation

Updated

September 8, 2026

JWT and Token Validation

Overview

JWTs are common bearer tokens. Most bugs are validation shortcuts: skipping exp, aud, iss, or accepting alg=none. Validate explicitly.

Use a maintained library (github.com/golang-jwt/jwt or similar); do not hand-roll crypto.

Minimal validation checklist

Claim / check Why
Signature + algorithm allowlist Integrity
exp / nbf Lifetime
iss Who minted
aud Intended recipient
sub present Principal id
// sketch with jwt/v5 style API
tok, err := jwt.Parse(tokenStr, func(t *jwt.Token) (any, error) {
    if t.Method.Alg() != jwt.SigningMethodHS256.Alg() {
        return nil, fmt.Errorf("unexpected alg")
    }
    return hmacSecret, nil
}, jwt.WithValidMethods([]string{"HS256"}),
    jwt.WithAudience("bookstore-api"),
    jwt.WithIssuer("auth.example.com"),
)

Access vs refresh

Token Lifetime Storage
Access minutes memory / short cookie
Refresh longer httpOnly cookie, rotate

Service-to-service

Prefer mTLS or short-lived minted tokens over eternal shared HS256 secrets across many services.

Rules of thumb

Do Don’t
Allowlist algorithms Trust alg header blindly
Validate aud/iss Only check signature
Short access TTL Multi-day bearer in localStorage without XSS plan

Try next

  1. Reject expired tokens in a unit test.
  2. Reject wrong aud.
  3. Document key rotation for HS256/RS256.