Secrets, cryptography and supply chain · 5 MIN READ

Design tokens deliberately: hashed opaque tokens, strictly verified signed tokens, expiry and rotation

Choose between opaque and signed tokens, store opaque tokens as hashes with rotation and reuse detection, and verify HMAC-signed JWTs with a pinned algorithm and checked claims.

The identity-authorization lesson says to validate a token's full contract before trusting the principal it names. This lesson designs the tokens themselves. Opaque tokens are random strings that mean nothing without a lookup, so revocation is immediate. Signed tokens carry their claims and verify without a lookup, so revocation is hard and every claim check is your job. Both need expiry, rotation and a plan for theft.

security · A MAP OF THE IDEA

  1. Choose opaque or signed
  2. Store hashes, rotate
  3. Pin alg, verify bytes
  4. Check exp, nbf, iss, aud

Useful when

  • Hashed opaque tokens are useless from a leaked table and revoke instantly.
  • A strict verifier rejects whole families of attacks by construction.

Watch out

  • Signed tokens stay valid until exp unless verifiers check a deny-list.
  • HMAC verifiers share the signing key and can therefore mint tokens.

Implementation & operation cost: A lookup per request for opaque tokens, or key distribution, short lifetimes and a refresh flow for signed ones; either way, a table of hostile test tokens to maintain.

01

Pick the token by who verifies it

If the service that issues a token is the only one that checks it, as with browser sessions or first-party API keys, use an opaque token: 32 random bytes, encoded, with all state kept on the server. Revocation is a row update, and the token reveals nothing about the user if it leaks into a log. Signed tokens such as JWTs earn their complexity when many services must verify independently without calling the issuer. The price is that a stolen signed token stays valid until it expires, unless every verifier also consults a revocation list, which brings the lookup back. Keep signed access tokens short-lived, minutes rather than days, and pair them with an opaque refresh token that the issuer can revoke.

02

Opaque tokens: store the digest, rotate on use

The store keeps only SHA-256 digests and is keyed by them, so a leaked table cannot be replayed and the lookup never compares the secret itself, as the constant-time lesson recommends. Refresh tokens rotate: each use returns a new token and marks the old one used. A second use of the same token means two parties hold it, so the whole family descending from that login is revoked. The clock is an injected function, which keeps expiry deterministic.

go
package main

import (
	"crypto/rand"
	"crypto/sha256"
	"encoding/base64"
	"errors"
	"fmt"
	"strings"
	"time"
)

var (
	errInvalid = errors.New("invalid token")
	errExpired = errors.New("token expired")
	errRevoked = errors.New("token revoked")
	errReuse   = errors.New("refresh token reused: family revoked")
)

type record struct {
	userID  string
	family  string // all tokens descended from one login
	expires time.Time
	used    bool
}

// Store keeps only SHA-256 digests. A leaked table cannot be replayed,
// and lookups never compare the secret itself.
type Store struct {
	byHash  map[[32]byte]*record
	revoked map[string]bool // revoked families
	now     func() time.Time
}

const prefix = "gfr_" // a recognizable prefix helps secret scanners

func (s *Store) issue(userID, family string, ttl time.Duration) string {
	raw := make([]byte, 32)
	rand.Read(raw)
	token := prefix + base64.RawURLEncoding.EncodeToString(raw)
	s.byHash[sha256.Sum256([]byte(token))] = &record{userID, family, s.now().Add(ttl), false}
	return token
}

func (s *Store) lookup(token string) (*record, error) {
	if !strings.HasPrefix(token, prefix) || len(token) != len(prefix)+43 {
		return nil, errInvalid
	}
	r, ok := s.byHash[sha256.Sum256([]byte(token))]
	switch {
	case !ok:
		return nil, errInvalid
	case s.revoked[r.family]:
		return nil, errRevoked
	case !s.now().Before(r.expires):
		return nil, errExpired
	}
	return r, nil
}

// Rotate exchanges a refresh token for a new one. Presenting an already
// used token means two parties hold it, so the whole family is revoked.
func (s *Store) Rotate(token string) (string, error) {
	r, err := s.lookup(token)
	if err != nil {
		return "", err
	}
	if r.used {
		s.revoked[r.family] = true
		return "", errReuse
	}
	r.used = true
	return s.issue(r.userID, r.family, 30*24*time.Hour), nil
}

func main() {
	now := time.Date(2026, 11, 18, 9, 0, 0, 0, time.UTC)
	s := &Store{byHash: map[[32]byte]*record{}, revoked: map[string]bool{}, now: func() time.Time { return now }}

	t1 := s.issue("user-42", "login-1", 30*24*time.Hour)
	fmt.Println("token length:", len(t1), "stored digest bytes:", len(sha256.Sum256([]byte(t1))))
	r, err := s.lookup(t1)
	fmt.Println("lookup:", r.userID, err)
	altered := []byte(t1)
	altered[10] ^= 0x01 // change one character
	_, err = s.lookup(string(altered))
	fmt.Println("altered:", err)

	t2, err := s.Rotate(t1)
	fmt.Println("rotated:", t2 != t1, err)
	_, err = s.Rotate(t1) // an attacker replays the stolen original
	fmt.Println("replay old:", err)
	_, err = s.Rotate(t2) // the legitimate client is logged out too
	fmt.Println("use new:", err)

	t3 := s.issue("user-7", "login-2", time.Hour)
	now = now.Add(61 * time.Minute)
	_, err = s.lookup(t3)
	fmt.Println("after 61 minutes:", err)
}
Read the code

issue draws 32 bytes from crypto/rand and adds a gfr_ prefix, giving 47 characters; a recognizable prefix lets secret scanners and log scrubbers find leaked tokens. lookup rejects the wrong shape before hashing, then checks family revocation and expiry against the injected clock. A one-character change misses the map entirely. Rotate returns a new token; replaying the original afterwards triggers reuse detection, which also invalidates the legitimate client's new token and forces a fresh login, a deliberate trade of convenience for containing theft. Moving the fixed clock forward 61 minutes expires the one-hour token.

03

A strict verifier for HMAC-signed tokens

When you must verify JWTs, prefer a maintained library and configure it strictly. The program shows what strict means using only the standard library: the algorithm is pinned by configuration, the header may contain only alg, typ and kid, the signature is checked over the exact received bytes before any claim is parsed, and exp is mandatory. It runs ten tokens, from valid to hostile, against a fixed clock and a test-only key.

go
package main

import (
	"bytes"
	"crypto/hmac"
	"crypto/sha256"
	"encoding/base64"
	"encoding/json"
	"errors"
	"fmt"
	"slices"
	"strings"
	"time"
)

var b64 = base64.RawURLEncoding.Strict()

type header struct {
	Alg string `json:"alg"`
	Typ string `json:"typ"`
	Kid string `json:"kid"`
}

type Claims struct {
	Iss string   `json:"iss"`
	Sub string   `json:"sub"`
	Aud audience `json:"aud"`
	Exp *int64   `json:"exp"`
	Nbf *int64   `json:"nbf"`
}

// audience accepts the two RFC 7519 shapes: "a" or ["a", "b"].
type audience []string

func (a *audience) UnmarshalJSON(b []byte) error {
	var one string
	if json.Unmarshal(b, &one) == nil {
		*a = audience{one}
		return nil
	}
	return json.Unmarshal(b, (*[]string)(a))
}

// Verifier accepts exactly one algorithm, issuer and audience.
type Verifier struct {
	Keys     map[string][]byte // kid -> HMAC key
	Issuer   string
	Audience string
	Leeway   time.Duration
	Now      func() time.Time
}

func base64URLOnly(s string) bool {
	for _, c := range s {
		if !('a' <= c && c <= 'z' || 'A' <= c && c <= 'Z' || '0' <= c && c <= '9' || c == '-' || c == '_') {
			return false
		}
	}
	return s != ""
}

func (v *Verifier) Verify(token string) (*Claims, error) {
	parts := strings.Split(token, ".")
	if len(parts) != 3 || !base64URLOnly(parts[0]) || !base64URLOnly(parts[1]) {
		return nil, errors.New("malformed token")
	}
	var h header
	if err := decodeStrict(parts[0], &h); err != nil {
		return nil, errors.New("malformed header")
	}
	if h.Alg != "HS256" { // pinned by configuration, never chosen by the token
		return nil, fmt.Errorf("unsupported alg %q", h.Alg)
	}
	if h.Typ != "at+jwt" {
		return nil, fmt.Errorf("unexpected typ %q", h.Typ)
	}
	key, ok := v.Keys[h.Kid]
	if !ok {
		return nil, errors.New("unknown key ID")
	}
	sig, err := b64.DecodeString(parts[2])
	if !base64URLOnly(parts[2]) || err != nil || !hmac.Equal(sig, mac(key, parts[0]+"."+parts[1])) {
		return nil, errors.New("invalid signature")
	}
	// Only bytes that passed the signature check are parsed as claims.
	var c Claims
	payload, err := b64.DecodeString(parts[1])
	if err != nil || json.Unmarshal(payload, &c) != nil {
		return nil, errors.New("malformed claims")
	}
	now := v.Now()
	switch {
	case c.Exp == nil:
		return nil, errors.New("missing exp")
	case !now.Before(time.Unix(*c.Exp, 0).Add(v.Leeway)):
		return nil, errors.New("token expired")
	case c.Nbf != nil && now.Add(v.Leeway).Before(time.Unix(*c.Nbf, 0)):
		return nil, errors.New("token not valid yet")
	case c.Iss != v.Issuer:
		return nil, errors.New("wrong issuer")
	case !slices.Contains(c.Aud, v.Audience):
		return nil, errors.New("wrong audience")
	}
	return &c, nil
}

// decodeStrict rejects header fields this verifier does not understand,
// such as "crit", "jku" or "jwk".
func decodeStrict(part string, v any) error {
	raw, err := b64.DecodeString(part)
	if err != nil {
		return err
	}
	dec := json.NewDecoder(bytes.NewReader(raw))
	dec.DisallowUnknownFields()
	return dec.Decode(v)
}

func mac(key []byte, signingInput string) []byte {
	m := hmac.New(sha256.New, key)
	m.Write([]byte(signingInput))
	return m.Sum(nil)
}

// sign builds test tokens, including deliberately hostile ones.
func sign(key []byte, h, claims string) string {
	in := b64.EncodeToString([]byte(h)) + "." + b64.EncodeToString([]byte(claims))
	return in + "." + b64.EncodeToString(mac(key, in))
}

func main() {
	key := []byte("test-only-key-32-bytes-long-0001") // test key, never a real secret
	now := time.Date(2026, 11, 18, 12, 0, 0, 0, time.UTC)
	v := &Verifier{Keys: map[string][]byte{"k1": key}, Issuer: "https://auth.example", Audience: "orders-api",
		Leeway: 30 * time.Second, Now: func() time.Time { return now }}

	hdr := `{"alg":"HS256","typ":"at+jwt","kid":"k1"}`
	claims := func(aud string, exp, nbf int64) string {
		return fmt.Sprintf(`{"iss":"https://auth.example","sub":"user-42","aud":%s,"exp":%d,"nbf":%d}`, aud, exp, nbf)
	}
	t := now.Unix()
	good := sign(key, hdr, claims(`["orders-api","billing-api"]`, t+300, t-60))
	parts := strings.Split(good, ".")
	forgedPayload := b64.EncodeToString([]byte(claims(`"orders-api"`, t+86400, t-60)))

	cases := []struct{ name, token string }{
		{"valid", good},
		{"alg none", b64.EncodeToString([]byte(`{"alg":"none","typ":"at+jwt","kid":"k1"}`)) + "." + parts[1] + "."},
		{"alg switch", sign(key, `{"alg":"HS512","typ":"at+jwt","kid":"k1"}`, claims(`"orders-api"`, t+300, t-60))},
		{"jku header", sign(key, `{"alg":"HS256","typ":"at+jwt","kid":"k1","jku":"https://evil.example/k"}`, claims(`"orders-api"`, t+300, t-60))},
		{"unknown kid", sign(key, `{"alg":"HS256","typ":"at+jwt","kid":"k9"}`, claims(`"orders-api"`, t+300, t-60))},
		{"edited payload", parts[0] + "." + forgedPayload + "." + parts[2]},
		{"expired", sign(key, hdr, claims(`"orders-api"`, t-31, t-600))},
		{"not yet valid", sign(key, hdr, claims(`"orders-api"`, t+600, t+120))},
		{"other audience", sign(key, hdr, claims(`"billing-api"`, t+300, t-60))},
		{"missing exp", sign(key, hdr, `{"iss":"https://auth.example","sub":"user-42","aud":"orders-api"}`)},
	}
	for _, c := range cases {
		got, err := v.Verify(c.token)
		if err != nil {
			fmt.Printf("%-15s rejected: %v\n", c.name, err)
			continue
		}
		fmt.Printf("%-15s accepted: sub=%s aud=%v\n", c.name, got.Sub, got.Aud)
	}
}
Read the code

This second program compiles as shown; run it in your own environment and it prints one accepted line followed by nine rejections. alg none and HS512 fail the pinned algorithm before any key is chosen, which is the defense against algorithm switching: the token never selects how it is verified. decodeStrict rejects the jku header, closing the family of attacks that inject keys or key URLs. The edited payload keeps the original signature and fails hmac.Equal. exp 31 seconds in the past exceeds the 30-second leeway; nbf two minutes ahead fails; an audience list without orders-api fails; and a token without exp is refused instead of treated as eternal. base64URLOnly matters because Go's base64 decoders ignore newlines even in Strict mode.

04

Expiry, revocation and key rotation in production

Give every token an absolute expiry and, for sessions, an idle timeout as well. Design revocation in from the start: for opaque tokens, delete or flag the record and revoke every family a user owns when the password changes; for signed tokens, keep lifetimes short or keep a deny-list of token IDs (jti) until their exp passes. Signing keys rotate through kid: publish the new key to verifiers first, start signing with it, and remove the old key only after the longest token lifetime has elapsed. Allow a clock-skew leeway of seconds, not hours. Use explicit typ values, such as at+jwt from RFC 9068 for access tokens, so an ID token or refresh token cannot be replayed where an access token is expected. Asymmetric algorithms such as EdDSA or ES256 let verifiers hold only public keys; with HMAC, every verifier can also mint tokens.

05

Hostile tokens for the test suite

Keep the ten cases from the verifier as table tests and add those a library might mishandle: alg in a different case, a kid that names a key meant for another purpose, an aud claim that is a number, exp as a float or a string, very long tokens, and a valid token presented to a different service. Go's encoding/json matches field names case-insensitively and keeps the last of duplicate keys, so another parser in your system might read a different exp or sub than you do; reject such payloads or make sure only one parser ever interprets the token. For opaque tokens, test expiry at the exact boundary, reuse detection, revocation after a password change, and that no code path stores or logs the raw token.

TAKE THIS WITH YOU

Prefer hashed opaque tokens when the issuer is the verifier; when tokens must be signed, pin the algorithm, verify the exact bytes before parsing, require exp, and check iss, aud and nbf against an injected clock.

Check your understanding

A verifier reads alg from the token header and uses it to decide how to check the signature. What is wrong with that?

Go to the source

Progress stays in this browser. No account needed.