- Storing long-lived bearer JWTs in localStorage exposes full account takeover to any single XSS gadget; keep access tokens in memory only.
- Refresh-token family tracking revokes the entire token lineage immediately if an already-rotated token is replayed by an attacker.
- FIDO2 passkeys eliminate phishing entirely because cryptographic signatures bind strictly to the browser-verified RP ID origin.
1. Why OAuth 2.0 Implicit Flow Is Dead and PKCE Is Mandatory Everywhere
Legacy Single Page Applications used OAuth 2.0 `response_type=token` (Implicit Grant), returning raw bearer access tokens directly inside URL `#access_token=...` fragments—leaking credentials into browser history, referrer headers, and analytics scripts. OAuth 2.1 retires Implicit Flow completely in favor of **Authorization Code Flow with PKCE (Proof Key for Code Exchange, RFC 7636)** using `S256` SHA-256 code challenges.
With PKCE, the browser generates a cryptographic 43–128 character random `code_verifier`, hashes it as `BASE64URL(SHA256(verifier))` for the initial `/authorize` redirect, and proves possession of the original `code_verifier` over a back-channel TLS POST when exchanging the single-use `code`. Even if a malicious browser extension or OS handler intercepts the authorization code, it cannot redeem it without the ephemeral verifier.
2. Refresh Token Family Tracking: Detecting Stolen Cookie Replay Immediately
Rotating a refresh token on every `/refresh` call raises a classic defensive question: *if an attacker steals Refresh Token `R_1` before the legitimate user refreshes, and the attacker uses `R_1` first (receiving `R_2`), what happens ten minutes later when the legitimate user’s browser presents `R_1`?*
If your server simply returns `401 Invalid Token` for `R_1`, the attacker keeps cruising indefinitely with `R_2`! **Refresh Token Family Tracking** solves this decisively: every login creates an immutable `FamilyId`. When an already-consumed token `R_1` is presented a second time (outside a tiny 2-second network idempotency grace window), the server recognizes active compromise and **revokes every active descendant (`R_2`, `R_3`...) sharing that `FamilyId` immediately**, forcing fresh FIDO2/2FA re-authentication.
public async Task<TokenPairResult> RotateRefreshTokenAsync(string rawToken, CancellationToken ct)
{
var tokenHash = Sha256Hex(rawToken);
var record = await refreshRepo.FindByHashAsync(tokenHash, ct);
if (record is null)
return TokenPairResult.Unauthorized("Unknown token");
if (record.ConsumedAtUtc is not null)
{
// Stolen predecessor token replayed! Revoke the ENTIRE token family immediately.
await refreshRepo.RevokeEntireFamilyAsync(record.FamilyId, reason: "ReplayReuseDetected", ct);
securityAudit.LogCritical("Refresh token replay detected for User={UserId} Family={FamilyId}",
record.UserId, record.FamilyId);
return TokenPairResult.CompromisedFamilyRevoked();
}
if (record.ExpiresAtUtc <= DateTime.UtcNow || record.RevokedAtUtc is not null)
return TokenPairResult.Unauthorized("Expired or revoked");
return await IssueRotatedSuccessorAtomicallyAsync(record, ct);
}3. FIDO2 WebAuthn Passkey Ceremonies: Phishing-Resistant Cryptography
Unlike TOTP 6-digit codes—which users routinely type into real-time adversary-in-the-middle phishing proxies—WebAuthn Passkeys are mathematically immune to phishing. During assertion (`navigator.credentials.get`), the operating system authenticator signs `clientDataJSON` containing the exact browser-verified `origin` (for example, `https://id.keshavsingh.in`) plus a single-use server `challenge` with a hardware/enclave-bound ECDSA P-256 or Ed25519 private key. A lookalike domain (`keshav-singh-login.com`) cannot even trigger the credential!
| Defense Layer | Vulnerable Default | Hardened Production Posture |
|---|---|---|
| Access Token Storage | localStorage.setItem("jwt", ...) | JavaScript closure / Angular signal memory only (<= 15m TTL) |
| Refresh Credential | Readable JS cookie or long JWT | HttpOnly; Secure; Path=/api/auth/refresh; Family-rotated |
| Second Factor | SMS OTP / Phishable 6-digit TOTP | FIDO2 WebAuthn Passkey (Origin-bound P-256 / Ed25519) |
| XSS Mitigation | Permissive script execution | Strict CSP + Angular DOM contextual escaping + Trusted Types |
4. Content Security Policy (CSP) & Referrer-Policy Checklist
Even clean token architecture benefits massively from browser-enforced HTTP response headers. Pairing `Referrer-Policy: strict-origin-when-cross-origin` (so full URL paths never leak to external links), `X-Content-Type-Options: nosniff`, `Permissions-Policy` disabling unused microphone/geolocation APIs, and a well-scoped `Content-Security-Policy` turns accidental XSS sinks into non-exploitable no-ops.
- Never pass bearer tokens or session IDs in URL query strings (`?token=...`), which leak into CDN logs and `Referer` headers.
- Validate JWT `iss` (Issuer), `aud` (Audience), `exp` (Expiration with `ClockSkew <= 30s`), and explicit `alg` allowlists on every resource API.
- Audit your own JWT access/refresh rotation cadence in our Developer Security Planner at /tools/cron-jwt-epoch-developer-toolkit.
Frequently Asked Questions
Why set ClockSkew = TimeSpan.FromSeconds(30) in Microsoft.AspNetCore.Authentication.JwtBearer?
ASP.NET Core defaults `TokenValidationParameters.ClockSkew` to 5 full minutes! Tightening `ClockSkew` to 15–30 seconds ensures a 15-minute access token actually expires at 15m30s instead of living silently for 20 minutes.
What happens if a user loses their laptop—are passkeys locked to one device?
Modern passkeys sync encrypted end-to-end across a user’s Apple iCloud Keychain, Google Password Manager, or 1Password vault, and we let users register multiple independent passkeys plus backup recovery verification.
Why scope the HttpOnly refresh cookie Path to /api/auth/refresh instead of Path=/ ?
Restricting `Path=/api/auth/refresh` prevents the browser from transmitting the high-value refresh cookie on every ordinary API call or image request—reducing both header overhead and accidental endpoint exposure.