100% 브라우저 메모리 연산 • 서버 로그 수집 제로 • 즉각적인 실행
Curious Techie개발자 툴박스
CORS9분 소요•한국어 Edition100% 브라우저 메모리 실행

CORS 및 동일 출처 정책(SOP)의 동작 원리

교차 출처 리소스 공유(CORS) 완벽 해설: 브라우저 프리플라이트 OPTIONS 요청, 응답 헤더 및 보안 취약점 방지.

CT
Curious-Techie Engineering Team검증된 작성자

Web Protocols & Security Architecture Research

발행일:
•
수정일:
•9분 소요
검토자: Curious-Techie Architecture Peer Review Group
핵심 질문 • 즉시 기술 답변

CORS 및 동일 출처 정책(SOP)의 동작 원리

TL;DR — 핵심 엔지니어링 요약

  • 동일 출처 정책(SOP)은 프로토콜, 호스트, 포트가 다른 출처의 리소스 응답을 읽지 못하도록 브라우저가 차단하는 보안 규칙입니다.
  • CORS는 백엔드 서버가 특정 외부 출처의 요청을 명시적으로 허용할 수 있게 해주는 표준 규격입니다.
  • 복잡한 요청 전송 시 브라우저는 먼저 OPTIONS 프리플라이트 요청을 전송하여 허용 여부를 사전 확인합니다.
  • 쿠키나 인증 헤더가 포함된 요청에서는 와일드카드 Access-Control-Allow-Origin: * 설정이 엄격히 금지됩니다.
  • CORS는 전적으로 클라이언트 웹 브라우저가 검증하고 강제하는 보안 메커니즘입니다.
// 기본 개념

핵심 개념 및 아키텍처 구조

Same-Origin Policy (SOP)

Boundary

The baseline security boundary isolating origins from reading each other’s DOM and network response payloads.

Preflight Request

Handshake

An automatic HTTP `OPTIONS` probe dispatched by the browser before the actual request to verify permissions.

Simple Request

Optimization

Requests utilizing standard methods (GET, HEAD, POST) with standard headers (Accept, Content-Type: text/plain, form-urlencoded, multipart) that bypass preflight.

Credentialed Requests

Auth

Requests sending HTTP cookies, TLS client certificates, or Authorization headers across origins.

Exposed Headers

Headers

Custom server headers (`Access-Control-Expose-Headers`) that the browser allows frontend JavaScript to read.

실행 흐름 • 동작 시퀀스

CORS 및 동일 출처 정책(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.

1

Origin Check

Browser identifies target URL origin differs from window.location origin.

Fetch from https://app.com -> https://api.com:443
2

Preflight 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, authorization
3

Server 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: 86400
4

Actual 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"}
5

Payload Delivery

Server returns response; browser checks `Access-Control-Allow-Origin` and delivers data to JS Promise.

const response = await fetch(...); // Promise resolves!
기술 예제 • 실전 구현

CORS 및 동일 출처 정책(SOP)의 동작 원리의 실무 구현 및 적용 방법

Complete Production Express.js CORS Middleware Implementation

javascript
import 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));

엔지니어링 상세 정보: Dynamic origin validation allowing credentialed requests without unsafe wildcards, with preflight caching for 24 hours.

Configuring Native Nginx CORS Response Headers

nginx
location /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;
}

엔지니어링 상세 정보: Handles OPTIONS preflight calls directly at Nginx edge layer with HTTP 204 No Content, reducing backend load.

프로덕션 아키텍처 • 실사례 연구

운영 환경에서 CORS 및 동일 출처 정책(SOP)의 동작 원리을 사용하는 이유와 구성

Decoupled JAMstack Frontend with Independent API Gateway

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.

Third-Party SaaS Embeddable Widgets

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.

안티패턴 및 주의사항

CORS 및 동일 출처 정책(SOP)의 동작 원리 구현 시 자주 발생하는 실수와 오해

안티패턴: Returning `Access-Control-Allow-Origin: *` alongside `Access-Control-Allow-Credentials: true`

영향도: Browsers strictly reject this combination for security; cross-origin call fails with fatal console error.

권장 해결책: Dynamically reflect the verified client `Origin` header value instead of the `*` wildcard when credentials are required.

안티패턴: Thinking CORS is a backend security firewall preventing scraping or hacking

영향도: Attackers bypass CORS completely using cURL, Python scripts, or mobile apps since non-browser clients ignore CORS.

권장 해결책: Enforce real backend authentication (JWTs, session tokens, rate limiting) rather than relying on CORS for security.

안티패턴: Failing to handle the HTTP `OPTIONS` method on the server routing table

영향도: Server returns 404 or 405 to the preflight probe; actual POST/PUT request is never allowed to fire.

권장 해결책: Ensure your server framework or API gateway explicitly responds to `OPTIONS` with status 200 or 204.

위협 모델링 • 공격 벡터

CORS 및 동일 출처 정책(SOP)의 동작 원리의 보안 영향 및 취약점 분석

Overly Permissive Cross-Origin Data Exfiltration

CWE-942 Permissive Cross-Domain Policy with Untrusted Domains

취약점: Server blindly reflects any incoming `Origin` header back into `Access-Control-Allow-Origin` with `credentials: true`.

완화 및 방어 전략: Validate incoming Origin headers against an explicit, strict allowlist of authorized company domains.

Internal Network Pivot via CORS

CWE-346 Origin Validation Error

취약점: Intranet server (e.g. `http://192.168.1.1`) responds with permissive CORS; malicious internet site uses visitor browser to read internal data.

완화 및 방어 전략: Implement Private Network Access (PNA) checks; restrict intranet APIs to local authentication tokens.
진단 워크플로 • 근본 원인 해결

CORS 및 동일 출처 정책(SOP)의 동작 원리 오류 진단 및 트러블슈팅 가이드

발생 증상 및 오류 징후: 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
프로덕션 검증 해결책: Mount CORS middleware at the very top of server middleware stack before routes; check server exception logs for 500 errors.

발생 증상 및 오류 징후: Custom response headers cannot be read via `response.headers.get()` in JavaScript

근본 원인 기술 분석:
  • Server omitted `Access-Control-Expose-Headers` for custom headers
프로덕션 검증 해결책: Include `Access-Control-Expose-Headers: X-Custom-Header, X-Total-Count` in the server response headers.
기술 지식베이스 • 즉시 답변

CORS 및 동일 출처 정책(SOP)의 동작 원리에 대한 자주 묻는 질문

Q:Why does CORS only happen in browsers and not in Postman or cURL?

핵심 요약 답변:CORS is a browser-enforced security mechanism designed to protect users from malicious websites using their browser session credentials. CLI tools like cURL do not execute untrusted foreign code, so they ignore CORS.

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?

핵심 요약 답변:A preflight request is an automated HTTP OPTIONS request sent by the browser before the real request. It is triggered whenever a request uses methods other than GET/HEAD/POST, sets custom headers (like Authorization), or uses non-standard Content-Types (like application/json).

The preflight allows the server to verify that it understands the method and headers before any payload data is processed on the backend.

섹션 12 • 대화형 실습 유틸리티

추천 관련 개발자 도구

100% 브라우저 메모리 실행

Companion Interactive Tool100% Client-Side Execution

Test & Verify with CORS Checker & Builder

Validate and generate secure Cross-Origin Resource Sharing (CORS) headers.

Companion Interactive Tool100% Client-Side Execution

Test & Verify with HTTP Header Analyzer

Analyze raw or live HTTP response headers for caching and architecture.

Companion Interactive Tool100% Client-Side Execution

Test & Verify with Security Headers Checker

Audit HSTS, CSP, X-Frame-Options, and OWASP recommended web headers.

용어사전

Origin
The unique combination of protocol, hostname, and port number.
Preflight
An HTTP OPTIONS request sent before the actual request to verify that the server permits it.
SOP
Same-Origin Policy: Browser security rule preventing scripts on one origin from accessing data on another.
Authoritative Sourcing & Verification

References & Primary Sources

Every source below directly substantiates technical statements and protocol behaviors explained in CORS 및 동일 출처 정책(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. [1]WHATWGPrimary SpecificationWHATWG Fetch • § 3.2 HTTP-network-fetch
    Verified Primary Source
    Technical 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. [2]IETFPrimary SpecificationRFC 9110 • § 9.2.1
    Verified Primary Source
    Technical 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. [3]OWASPAuthoritative Security StandardOWASP Cheat Sheet Series • Origin Validation & Credentials
    Verified Primary Source
    Technical Claim Supported:

    Documents the security risks of dynamic origin reflection without strict server-side allowlist verification (CORS misconfiguration vulnerabilities).

  4. [4]MDNDeveloper Authority (MDN)MDN Web Docs • CORS Preflight & Simple Requests
    Verified Primary Source
    Technical Claim Supported:

    Provides developer reference for simple requests vs. preflighted requests and safelisted headers (Accept, Accept-Language, Content-Language, Content-Type).