Working with Security Tokens

1. Understanding Security Token Types

TokenPurposeLifetime
AccessAPI authorizationMinutes
RefreshGet new accessDays–months
ID TokenIdentity assertion (OIDC)Minutes
CSRFAnti-CSRFPer session/request
One-time (OTP, magic link)Single-use actionMinutes
Authorization codeOAuth code flow≤10 min, single use
Device codeDevice auth flow5–15 min
SAML assertionSSO identityMinutes

2. Generating Cryptographically Secure Tokens

Example: CSPRNG token generation

// Node.js
import { randomBytes } from "crypto";
const token = randomBytes(32).toString("base64url");   // 256 bits

// Java
SecureRandom rng = new SecureRandom();
byte[] buf = new byte[32];
rng.nextBytes(buf);
String token = Base64.getUrlEncoder().withoutPadding().encodeToString(buf);

// Python
import secrets
token = secrets.token_urlsafe(32)
Use CaseMin Entropy
Session ID128 bits
CSRF token128 bits
Refresh token256 bits
Email/reset token128 bits

3. Using UUID for Token Generation

UUID VersionSource of bitsUse for tokens?
v1Time + MACNo (predictable)
v4122 random bitsOK (entropy < 256 bit ideal)
v7 NEWTime + randomFor sortable IDs, not secrets
CSPRNG bytes256-bit randomBest for secrets

4. Implementing Token Storage

TokenStorage
Long-lived secretsHSM / KMS
Refresh tokensDB (hashed)
Short-lived (auth code)Redis with TTL
CSRF tokensSession store or signed cookie

5. Validating Token Integrity

MechanismUse Case
HMAC-SHA256Symmetric authentication
Digital signature (RSA/ECDSA)Asymmetric, public verify
AEAD (AES-GCM)Confidentiality + integrity
ComparisonAlways constant-time

6. Setting Token Expiration

TokenTTL
Email verification24 hr
Password reset15 min
Magic link login10 min
OTP30–60 sec (TOTP), 5–10 min (HOTP/SMS)
Device pairing5–15 min

7. Implementing One-Time Tokens

async function consumeToken(raw) {
  const hash = sha256(raw);
  // Atomic delete-if-exists ensures single use
  const result = await db.query(
    "DELETE FROM tokens WHERE token_hash=$1 AND expires_at > NOW() RETURNING user_id",
    [hash]
  );
  if (!result.rowCount) throw new Error("invalid_or_expired");
  return result.rows[0].user_id;
}

8. Using Signed Tokens

ApproachTradeoff
HMACStateless, but secret distribution issue
Signed cookie (PASETO)Modern alt to JWT, no algorithm confusion
JWSStandard, ecosystem support

9. Implementing Token Encryption

AlgorithmNotes
AES-256-GCMAEAD, modern default
ChaCha20-Poly1305Fast on devices without AES-NI
XChaCha20-Poly1305Larger nonce (random-safe)
RSA-OAEP / ECDH-ESKey wrap for JWE

10. Preventing Token Enumeration Attacks

VulnerabilityMitigation
Sequential IDsUse random opaque tokens
Predictable formatCSPRNG only
Timing differencesConstant-time lookup + comparison
Token in URLUse POST body or Authorization header
Logged tokensScrub from access logs