FastAPI Next.js Express OAuth 2.0 #open-redirect #csrf #cookies #headers

OAuth Open Redirect, CSRF & Session Cookie Hardening

Eliminate login open redirects (?next=//evil.com), lock down Set-Cookie attributes, and enforce strict HSTS and clickjacking defenses.

View /llms.txt View /llms-full.txt

Why This Matters

Attackers abuse unvalidated ?next=, ?redirect_to=, and ?returnUrl= parameters on /login to phish users after a legitimate OAuth or password login, or bypass cookie isolation when HttpOnly, Secure, and SameSite flags are missing.

Hardening Checklist for AI Agents

  1. Strictly validate post-login redirects — accept only relative paths starting with a single / and NOT // or /\, or match against an exact hostname allowlist.
  2. Enforce __Host- prefix for session cookies in HTTPS production (Secure; HttpOnly; SameSite=Lax; Path=/, no Domain attribute).
  3. Send Strict-Transport-Security: max-age=31536000; includeSubDomains over HTTPS.
  4. Block clickjacking on /login with Content-Security-Policy: frame-ancestors 'none' AND X-Frame-Options: DENY.
  5. Add X-Content-Type-Options: nosniff and Referrer-Policy: strict-origin-when-cross-origin so OAuth state/code query parameters never leak in Referer headers.

Reference Python / TypeScript Safe Redirect Validator

from urllib.parse import urlparse


def safe_redirect_target(raw_target: str | None, fallback: str = "/dashboard") -> str:
    if not raw_target:
        return fallback
    candidate = raw_target.strip()
    # Reject protocol-relative //evil.com, backslash tricks /\evil.com, and full URLs
    if not candidate.startswith("/") or candidate.startswith("//") or candidate.startswith("/\\"):
        return fallback
    parsed = urlparse(candidate)
    if parsed.scheme or parsed.netloc:
        return fallback
    return candidate
export function safeRedirectTarget(rawTarget: string | null | undefined, fallback = "/dashboard"): string {
  if (!rawTarget) return fallback;
  const candidate = rawTarget.trim();
  if (!candidate.startsWith("/") || candidate.startsWith("//") || candidate.startsWith("/\\")) {
    return fallback;
  }
  try {
    const parsed = new URL(candidate, "https://placeholder.local");
    if (parsed.origin !== "https://placeholder.local") return fallback;
    return `${parsed.pathname}${parsed.search}${parsed.hash}`;
  } catch {
    return fallback;
  }
}

Verification Steps

View raw SKILL.md markdown
## Why This Matters

Attackers abuse unvalidated `?next=`, `?redirect_to=`, and `?returnUrl=` parameters on `/login` to phish users after a legitimate OAuth or password login, or bypass cookie isolation when `HttpOnly`, `Secure`, and `SameSite` flags are missing.

## Hardening Checklist for AI Agents

1. **Strictly validate post-login redirects** — accept only relative paths starting with a single `/` and NOT `//` or `/\`, or match against an exact hostname allowlist.
2. **Enforce `__Host-` prefix for session cookies** in HTTPS production (`Secure; HttpOnly; SameSite=Lax; Path=/`, no `Domain` attribute).
3. **Send `Strict-Transport-Security: max-age=31536000; includeSubDomains`** over HTTPS.
4. **Block clickjacking** on `/login` with `Content-Security-Policy: frame-ancestors 'none'` AND `X-Frame-Options: DENY`.
5. **Add `X-Content-Type-Options: nosniff` and `Referrer-Policy: strict-origin-when-cross-origin`** so OAuth `state`/`code` query parameters never leak in `Referer` headers.

## Reference Python / TypeScript Safe Redirect Validator

```python
from urllib.parse import urlparse


def safe_redirect_target(raw_target: str | None, fallback: str = "/dashboard") -> str:
    if not raw_target:
        return fallback
    candidate = raw_target.strip()
    # Reject protocol-relative //evil.com, backslash tricks /\evil.com, and full URLs
    if not candidate.startswith("/") or candidate.startswith("//") or candidate.startswith("/\\"):
        return fallback
    parsed = urlparse(candidate)
    if parsed.scheme or parsed.netloc:
        return fallback
    return candidate
```

```ts
export function safeRedirectTarget(rawTarget: string | null | undefined, fallback = "/dashboard"): string {
  if (!rawTarget) return fallback;
  const candidate = rawTarget.trim();
  if (!candidate.startsWith("/") || candidate.startsWith("//") || candidate.startsWith("/\\")) {
    return fallback;
  }
  try {
    const parsed = new URL(candidate, "https://placeholder.local");
    if (parsed.origin !== "https://placeholder.local") return fallback;
    return `${parsed.pathname}${parsed.search}${parsed.hash}`;
  } catch {
    return fallback;
  }
}
```

## Verification Steps

- Test `GET /login?next=https://example.invalid` and `GET /login?redirect_to=//example.invalid` — confirm `Location` never points to `example.invalid`.
- Inspect `curl -I https://example.com/login` — verify `Strict-Transport-Security`, `X-Frame-Options`, `Content-Security-Policy: frame-ancestors`, and `X-Content-Type-Options: nosniff`.