O que é CORS e a Política de Mesma Origem (SOP)?
Entenda o Cross-Origin Resource Sharing: requisições preflight OPTIONS, cabeçalhos de controle e prevenção de falhas de segurança.
Web Protocols & Security Architecture Research
O que é CORS e a Política de Mesma Origem (SOP)?
TL;DR — Principais Conclusões de Engenharia
- A Política de Mesma Origem (SOP) impede scripts de ler respostas de origens com protocolo, domínio ou porta divergentes.
- O CORS é o mecanismo pelo qual servidores declaram quais origens externas têm permissão para consumir suas APIs.
- Requisições preflight
OPTIONSverificam métodos e cabeçalhos antes do envio de chamadas potencialmente perigosas. - O uso de
Access-Control-Allow-Origin: *é estritamente bloqueado quando há envio de cookies ou tokens autenticados. - O CORS é verificado e aplicado pelo navegador web do cliente, não por requisições diretas servidor para servidor.
Conceitos Centrais e Arquitetura
Same-Origin Policy (SOP)
BoundaryThe baseline security boundary isolating origins from reading each other’s DOM and network response payloads.
Preflight Request
HandshakeAn automatic HTTP `OPTIONS` probe dispatched by the browser before the actual request to verify permissions.
Simple Request
OptimizationRequests utilizing standard methods (GET, HEAD, POST) with standard headers (Accept, Content-Type: text/plain, form-urlencoded, multipart) that bypass preflight.
Credentialed Requests
AuthRequests sending HTTP cookies, TLS client certificates, or Authorization headers across origins.
Exposed Headers
HeadersCustom server headers (`Access-Control-Expose-Headers`) that the browser allows frontend JavaScript to read.
Como funciona O que é CORS e a Política de Mesma Origem (SOP)??
When JavaScript triggers a fetch request to a different origin, the browser evaluates whether the request is "simple" or "complex". If complex (e.g., custom headers or JSON content-type), the browser automatically dispatches an `OPTIONS` preflight request with `Origin`, `Access-Control-Request-Method`, and `Access-Control-Request-Headers`. If the server responds with matching `Access-Control-Allow-*` headers, the browser fires the actual request. If not, the browser blocks the response from frontend JS.
Origin Check
Browser identifies target URL origin differs from window.location origin.
Fetch from https://app.com -> https://api.com:443Preflight OPTIONS Dispatch
Browser sends HTTP OPTIONS probe with requested method and headers.
OPTIONS /api/data HTTP/1.1
Origin: https://app.com
Access-Control-Request-Method: POST
Access-Control-Request-Headers: content-type, authorizationServer Header Validation
Server inspects Origin, checks authorized list, and returns approval headers.
HTTP/1.1 204 No Content
Access-Control-Allow-Origin: https://app.com
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: Content-Type, Authorization
Access-Control-Max-Age: 86400Actual Request Execution
Browser verifies preflight response matches, then transmits actual POST request.
POST /api/data HTTP/1.1
Origin: https://app.com
Content-Type: application/json
{"data": "payload"}Payload Delivery
Server returns response; browser checks `Access-Control-Allow-Origin` and delivers data to JS Promise.
const response = await fetch(...); // Promise resolves!Como implementar O que é CORS e a Política de Mesma Origem (SOP)? na prática?
Complete Production Express.js CORS Middleware Implementation
javascriptimport cors from "cors";
import express from "express";
const app = express();
const allowedOrigins = [
"https://curious-techie.com",
"https://staging.curious-techie.com",
];
const corsOptions = {
origin: (origin, callback) => {
// Allow requests with no origin (e.g. mobile apps or server-to-server)
if (!origin || allowedOrigins.includes(origin)) {
callback(null, true);
} else {
callback(new Error("Blocked by CORS policy"));
}
},
methods: ["GET", "POST", "PUT", "DELETE", "PATCH", "OPTIONS"],
allowedHeaders: ["Content-Type", "Authorization", "X-Requested-With"],
exposedHeaders: ["X-Total-Count", "Content-Disposition"],
credentials: true,
maxAge: 86400, // Cache preflight for 24 hours
};
app.use(cors(corsOptions));Detalhes de Engenharia: Dynamic origin validation allowing credentialed requests without unsafe wildcards, with preflight caching for 24 hours.
Configuring Native Nginx CORS Response Headers
nginxlocation /api/ {
if ($request_method = 'OPTIONS') {
add_header 'Access-Control-Allow-Origin' '$http_origin' always;
add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE' always;
add_header 'Access-Control-Allow-Headers' 'Authorization, Content-Type, Accept' always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
add_header 'Access-Control-Max-Age' 86400 always;
add_header 'Content-Length' 0;
add_header 'Content-Type' 'text/plain charset=UTF-8';
return 204;
}
add_header 'Access-Control-Allow-Origin' '$http_origin' always;
add_header 'Access-Control-Allow-Credentials' 'true' always;
proxy_pass http://backend_upstream;
}Detalhes de Engenharia: Handles OPTIONS preflight calls directly at Nginx edge layer with HTTP 204 No Content, reducing backend load.
Onde e por que O que é CORS e a Política de Mesma Origem (SOP)? é usado em produção?
Next.js frontend hosted on Vercel (`app.curious-techie.com`) calling a Go backend on AWS (`api.curious-techie.com`).
Subdomain crossing constitutes a cross-origin call; the Go backend returns explicit CORS headers allowing the frontend origin.
Chat widget or analytics SDK installed on thousands of customer websites.
API server must return `Access-Control-Allow-Origin: *` since requests originate from arbitrary customer hostnames.
Quais são os erros comuns com O que é CORS e a Política de Mesma Origem (SOP)??
Impacto: Browsers strictly reject this combination for security; cross-origin call fails with fatal console error.
Correção Recomendada: Dynamically reflect the verified client `Origin` header value instead of the `*` wildcard when credentials are required.
Impacto: Attackers bypass CORS completely using cURL, Python scripts, or mobile apps since non-browser clients ignore CORS.
Correção Recomendada: Enforce real backend authentication (JWTs, session tokens, rate limiting) rather than relying on CORS for security.
Impacto: Server returns 404 or 405 to the preflight probe; actual POST/PUT request is never allowed to fire.
Correção Recomendada: Ensure your server framework or API gateway explicitly responds to `OPTIONS` with status 200 or 204.
Quais são as implicações e riscos de segurança de O que é CORS e a Política de Mesma Origem (SOP)??
Overly Permissive Cross-Origin Data Exfiltration
CWE-942 Permissive Cross-Domain Policy with Untrusted DomainsVulnerabilidade: Server blindly reflects any incoming `Origin` header back into `Access-Control-Allow-Origin` with `credentials: true`.
Internal Network Pivot via CORS
CWE-346 Origin Validation ErrorVulnerabilidade: Intranet server (e.g. `http://192.168.1.1`) responds with permissive CORS; malicious internet site uses visitor browser to read internal data.
Como diagnosticar e resolver erros com O que é CORS e a Política de Mesma Origem (SOP)??
Sintomas e Indicações Clínicas: Console Error: "No 'Access-Control-Allow-Origin' header is present on the requested resource"
- Server threw an unhandled 500 exception before CORS middleware ran
- CORS middleware placed after route handlers
Sintomas e Indicações Clínicas: Custom response headers cannot be read via `response.headers.get()` in JavaScript
- Server omitted `Access-Control-Expose-Headers` for custom headers
Perguntas Frequentes sobre O que é CORS e a Política de Mesma Origem (SOP)?
Q:Why does CORS only happen in browsers and not in Postman or cURL?
In a browser, you might visit `evil.com` while logged into `yourbank.com`. Without SOP and CORS, JavaScript on `evil.com` could fetch data from `yourbank.com` using your browser session cookies. Postman doesn’t have this security hazard.
Q:What is a Preflight request and when is it triggered?
The preflight allows the server to verify that it understands the method and headers before any payload data is processed on the backend.
Ferramentas Relacionadas
Execução 100% no Cliente
Glossário
References & Primary Sources
Every source below directly substantiates technical statements and protocol behaviors explained in O que é CORS e a Política de Mesma Origem (SOP)?. Curious-Techie prioritizes official Internet standards (IETF RFCs, W3C Recommendations, WHATWG specifications) and established security bodies (OWASP, NIST). Zero sponsored or secondary links.
- [1]WHATWGPrimary SpecificationWHATWG Fetch • § 3.2 HTTP-network-fetchVerified Primary SourceTechnical Claim Supported:
Defines the normative browser CORS protocol, preflight cache validation (Access-Control-Max-Age), and the prohibition of wildcard Access-Control-Allow-Origin: * when Access-Control-Allow-Credentials is true.
“For a CORS request with credentials, the server cannot specify a wildcard for Access-Control-Allow-Origin. It must specify an explicit origin.” - [2]IETFPrimary SpecificationRFC 9110 • § 9.2.1Verified Primary SourceTechnical Claim Supported:
Specifies that the Origin request header indicates the scheme, host, and port of the originating context and must not be altered by user-agent JavaScript.
- [3]OWASPAuthoritative Security StandardOWASP Cheat Sheet Series • Origin Validation & CredentialsVerified Primary SourceTechnical Claim Supported:
Documents the security risks of dynamic origin reflection without strict server-side allowlist verification (CORS misconfiguration vulnerabilities).
- [4]MDNDeveloper Authority (MDN)MDN Web Docs • CORS Preflight & Simple RequestsVerified Primary SourceTechnical Claim Supported:
Provides developer reference for simple requests vs. preflighted requests and safelisted headers (Accept, Accept-Language, Content-Language, Content-Type).
Ecossistema Técnico Relacionado e Próximos Passos
Ferramentas Relacionadas
Artigos Técnicos Relacionados
CSP vs CORS: Differences in Browser Defense Mechanisms
Distinguishing outbound resource loading restrictions from inbound server access control.
Troubleshooting: No Access-Control-Allow-Origin Header Present
Diagnose and fix the most common browser cross-origin blocking error with production configs.
Perguntas Relacionadas
Why Does CORS Allow Simple GET Requests Without a Preflight?
Answer: CORS allows simple GET requests without preflight for backwards compatibility with legacy HTML form and image behaviors that predate CORS.
Why Do Browsers Send OPTIONS Preflight Requests?
Answer: Browsers send preflights to verify that older servers not expecting cross-origin calls explicitly permit the method and custom headers before execution.
Especificações e Referências para Desenvolvedores
Continuar Aprendendo
CORS Policy & Preflight Handshake Lab
Simulate preflight OPTIONS probes and adjust Access-Control-Allow-* headers inside the browser sandbox.