Implementing Secure Authentication Flows

1. Understanding Flow Security

ThreatMitigation
Authorization code interceptionPKCE
CSRF on callbackstate parameter
Token replaynonce (OIDC), DPoP
Open redirectExact-match redirect_uri
MitMTLS, 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

PurposeDetail
CSRFBind authorization request to session
GenerationCrypto-random ≥ 128 bits
StorageCookie/session before redirect
VerificationCompare on callback; reject mismatch

4. Implementing Nonce for OIDC

PurposeDetail
Replay preventionID token nonce claim matches sent value
RequiredFor implicit / hybrid flows
RecommendedFor code flow too

5. Validating Redirect URIs

RuleDetail
Exact matchCompare full URI string (RFC 9700)
No wildcardsSubdomain wildcards = vulnerability
HTTPS onlyExcept 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

StandardDetail
JAR (RFC 9101)JWT-encoded OAuth authorization request
PAR (RFC 9126)Pushed Authorization Requests
FAPI 2.0Financial-grade — mandates JAR/PAR

8. Using Challenge-Response Authentication

UseExample
WebAuthnServer sends challenge; authenticator signs
SCRAMSASL challenge-response (RFC 5802)
PropertyNo password sent; replay resistant

9. Implementing Time-Based Validation

ClaimWindow
iat (issued at)Reject if too old
expStrict — no future use
nbf (not before)Reject if in future
SkewAllow ±60s clock drift

10. Handling Man-in-the-Middle Attacks

DefenseDetail
TLS 1.3Only modern ciphers; HSTS
Cert pinningMobile apps
DPoP / mTLS-bound tokensSender-constrained tokens
CT logsDetect rogue certs