Implementing Cross-Origin Authentication
1. Understanding CORS
| Concept | Detail |
| Same-origin policy | Browser default — restrict cross-origin requests |
| CORS | Server opt-in to allow specific origins |
| Simple | GET/POST/HEAD with safelisted headers/content-types |
| Preflight | OPTIONS for non-simple requests |
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
| Header | Detail |
| Access-Control-Allow-Origin | Echo specific origin (not * with creds) |
| Access-Control-Allow-Methods | List of allowed methods |
| Access-Control-Allow-Headers | List of allowed request headers |
| Access-Control-Max-Age | Cache preflight (seconds) |
4. Using Credentials with CORS
| Side | Required |
| Client | fetch(url, { credentials: "include" }) |
| Server | Access-Control-Allow-Credentials: true |
| Origin | Must be specific (not *) |
5. Implementing Cross-Domain Cookies
| Attribute | Required |
| SameSite=None | Allow cross-site |
| Secure | Required with SameSite=None |
| Partitioned | CHIPS — 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
| Pattern | Detail |
| Silent renew | Hidden iframe to IdP with prompt=none |
| Sandbox | sandbox="allow-scripts allow-same-origin" |
| 3P cookies | Often blocked — prefer refresh tokens / BFF |
8. Handling Third-Party Cookie Restrictions
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
| Pattern | Detail |
| BFF | Same-origin endpoint proxies to API |
| Auth | HttpOnly cookie at proxy; token attached server-side |
| Benefit | Avoids 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