Implementing Cross-Origin Authentication

1. Understanding CORS

ConceptDetail
Same-origin policyBrowser default — restrict cross-origin requests
CORSServer opt-in to allow specific origins
SimpleGET/POST/HEAD with safelisted headers/content-types
PreflightOPTIONS for non-simple requests

2. Implementing CORS Headers

Example: Express CORS config

app.use(cors({
  origin: ["https://app.example.com"],          // never "*" with credentials
  credentials: true,
  methods: ["GET","POST","PUT","DELETE"],
  allowedHeaders: ["Authorization","Content-Type"],
  exposedHeaders: ["X-Request-Id"],
  maxAge: 600
}));

3. Handling Preflight Requests

HeaderDetail
Access-Control-Allow-OriginEcho specific origin (not * with creds)
Access-Control-Allow-MethodsList of allowed methods
Access-Control-Allow-HeadersList of allowed request headers
Access-Control-Max-AgeCache preflight (seconds)

4. Using Credentials with CORS

SideRequired
Clientfetch(url, { credentials: "include" })
ServerAccess-Control-Allow-Credentials: true
OriginMust be specific (not *)

5. Implementing Cross-Domain Cookies

AttributeRequired
SameSite=NoneAllow cross-site
SecureRequired with SameSite=None
PartitionedCHIPS — per top-level partition (Chrome 3PCD)

6. Working with postMessage for Auth

Example: Validate sender

window.addEventListener("message", (e) => {
  if (e.origin !== "https://auth.example") return;
  if (e.data?.type === "auth.token") setToken(e.data.token);
});

7. Implementing iframe Authentication

PatternDetail
Silent renewHidden iframe to IdP with prompt=none
Sandboxsandbox="allow-scripts allow-same-origin"
3P cookiesOften blocked — prefer refresh tokens / BFF
Warning: Chrome's third-party cookie deprecation (2024-2025+) breaks many federation flows. Migrate to BFF, FedCM, or Storage Access API.

9. Implementing Proxy Endpoints

PatternDetail
BFFSame-origin endpoint proxies to API
AuthHttpOnly cookie at proxy; token attached server-side
BenefitAvoids CORS, no token in browser JS

10. Cross-Origin Best Practices

  • Allowlist exact origins; never reflect arbitrary Origin
  • Avoid * with credentials
  • Prefer same-origin + BFF for SPAs
  • Validate Origin/Referer on state-changing endpoints (CSRF defense)
  • Set Cross-Origin-Opener-Policy, Cross-Origin-Resource-Policy