JSON Web Tokens (JWTs) enable stateless authentication. Here's how to implement them securely.
JWT Structure#
Header.Payload.Signature
Header:
{
"alg": "HS256",
"typ": "JWT"
}
Payload:
{
"sub": "user123",
"iat": 1704067200,
"exp": 1704070800,
"role": "user"
}
Signature:
HMACSHA256(
base64UrlEncode(header) + "." + base64UrlEncode(payload),
secret
)
Token Creation#
Token Validation#
Refresh Token Flow#
Token Revocation#
Cookie-Based Tokens#
Client-Side Token Management#
Security Best Practices#
Tokens:
✓ Short-lived access tokens (15 minutes)
✓ Longer-lived refresh tokens (7 days)
✓ Rotate refresh tokens on use
✓ Store refresh tokens in database
Storage:
✓ HttpOnly cookies for refresh tokens
✓ Memory for access tokens (not localStorage)
✓ Secure flag in production
✓ SameSite=Strict
Validation:
✓ Verify signature, issuer, audience
✓ Check expiration
✓ Validate user still exists
✓ Handle token revocation
General:
✓ Use strong secrets (256+ bits)
✓ Different secrets for access/refresh
✓ Implement logout from all devices
✓ Rotate tokens on password change
Conclusion#
JWT authentication requires careful implementation. Use short-lived access tokens with longer-lived refresh tokens. Store refresh tokens in HTTP-only cookies, rotate them on use, and implement proper revocation. Never store JWTs in localStorage—use memory or secure cookies.