Implementing Secure Authentication Flows
1. Understanding Flow Security
| Threat | Mitigation |
| Authorization code interception | PKCE |
| CSRF on callback | state parameter |
| Token replay | nonce (OIDC), DPoP |
| Open redirect | Exact-match redirect_uri |
| MitM | TLS, certificate pinning |
2. Implementing PKCE for OAuth
Example: PKCE pair
const verifier = base64url(crypto.randomBytes(32));
const challenge = base64url(sha256(verifier));
// /authorize?code_challenge=...&code_challenge_method=S256
// /token request includes code_verifier
REQUIRED 2026 for all OAuth 2.1 clients (RFC 9700 BCP).
3. Using State Parameter
| Purpose | Detail |
| CSRF | Bind authorization request to session |
| Generation | Crypto-random ≥ 128 bits |
| Storage | Cookie/session before redirect |
| Verification | Compare on callback; reject mismatch |
4. Implementing Nonce for OIDC
| Purpose | Detail |
| Replay prevention | ID token nonce claim matches sent value |
| Required | For implicit / hybrid flows |
| Recommended | For code flow too |
5. Validating Redirect URIs
| Rule | Detail |
| Exact match | Compare full URI string (RFC 9700) |
| No wildcards | Subdomain wildcards = vulnerability |
| HTTPS only | Except http://localhost for dev |
6. Preventing Open Redirect Attacks
Example: Safe redirect
const ALLOWED = new Set(["/dashboard","/orders","/profile"]);
const next = req.query.next;
res.redirect(ALLOWED.has(next) ? next : "/dashboard");
7. Implementing Request Signing
| Standard | Detail |
| JAR (RFC 9101) | JWT-encoded OAuth authorization request |
| PAR (RFC 9126) | Pushed Authorization Requests |
| FAPI 2.0 | Financial-grade — mandates JAR/PAR |
8. Using Challenge-Response Authentication
| Use | Example |
| WebAuthn | Server sends challenge; authenticator signs |
| SCRAM | SASL challenge-response (RFC 5802) |
| Property | No password sent; replay resistant |
9. Implementing Time-Based Validation
| Claim | Window |
| iat (issued at) | Reject if too old |
| exp | Strict — no future use |
| nbf (not before) | Reject if in future |
| Skew | Allow ±60s clock drift |
10. Handling Man-in-the-Middle Attacks
| Defense | Detail |
| TLS 1.3 | Only modern ciphers; HSTS |
| Cert pinning | Mobile apps |
| DPoP / mTLS-bound tokens | Sender-constrained tokens |
| CT logs | Detect rogue certs |