CORS(Cross-Origin Resource Sharing)
μΉ μ ν리μΌμ΄μ μ 보μμ μν΄ κΈ°λ³Έμ μΌλ‘ λμΌ μΆμ² μ μ± (SOP)μ λ°λ₯΄μ§λ§, λ€λ₯Έ μΆμ²μ 리μμ€λ₯Ό μ¬μ©ν΄μΌ νλ μ λΉν μν©(API νΈμΆ λ±)μ μν΄ κ³ μλ μμΈ μ‘°νμ΄μ 보μ λ©μ»€λμ¦μ΄λ€.
Same-Origin Policy(λμΌ μΆμ² μ μ±
)
λΈλΌμ°μ λ 보μμμ μ΄μ λ‘ μ€ν¬λ¦½νΈμμ μμλ κ΅μ°¨ μΆμ² HTTP μμ²μ μ ννλ Same-Origin Policy(SOP) μ μ± μ λ°λ₯Έλ€.
μΆμ²(Origin)μ μ μ
μΆμ²λ μλμ μμλ€λ‘ ꡬμ±λλ©°, μ΄ μ€ νλλΌλ λ€λ₯΄λ©΄ λ€λ₯Έ μΆμ²(Cross-Origin)λ‘ κ°μ£Όλλ€.
λ€λ₯Έ λλ©μΈ (example.com - test.com)
λ€λ₯Έ νμ λλ©μΈ (example.com - store.example.com)
λ€λ₯Έ ν¬νΈ (example.com:80 - example.com:90)
λ€λ₯Έ νλ‘ν μ½ (https://example.com - http://example.com)
μ¬κΈ°μ https://example.comκ³Ό https://www.example.comλ λ€λ₯Έ λλ©μΈμΌλ‘ κ°μ£ΌλκΈ° λλ¬Έμ μ£Όμν΄μΌνλ€.
μμ(κΈ°μ€ http://store.ogufamily.com)
http://store.ogufamily.com)http://store.ogufamily.com/babyogu.html
same origin
pathλ§ λ€λ₯Έκ²½μ°
http://store.ogufamily.com/ogu.html
same origin
pathλ§ λ€λ₯Έκ²½μ°
https://store.ogufamily.com
cross origin
νλ‘ν μ½μ΄ λ€λ₯Έ κ²½μ°
http://store.ogufamily.com:81
cross origin
ν¬νΈκ° λ€λ₯Έκ²½μ°
http://news.ogufamily.com
cross origin
λλ©μΈμ΄ λ€λ₯Έκ²½μ°
CORS λμ μλ리μ€
CORS μμ²μ λΈλΌμ°μ κ° μλμΌλ‘ μ²λ¦¬νλ©°, μμ²μ μ±κ²©μ λ°λΌ ν¬κ² μΈ κ°μ§ μλ리μ€λ‘ λλλ€.
1. Simple Request (λ¨μ μμ²)
μλΉ μμ²(Preflight) μμ΄ λ°λ‘ λ³Έ μμ²μ 보λ΄λ λ°©μμ΄λ€. μλ 쑰건μ λͺ¨λ λ§μ‘±ν΄μΌ νλ€.
λ©μλ: GET, HEAD, POST μ€ νλ
ν€λ: Accept, Accept-Language, Content-Language, Content-Type λ± νμ©λ ν€λλ§ μ¬μ©
Content-Type:
application/x-www-form-urlencoded,multipart/form-data,text/plainμ€ νλ
νμ§λ§ μ΅μ μΉ APIλ λλΆλΆ application/jsonμ μ¬μ©νλ―λ‘ λ¨μ μμ² μ‘°κ±΄μ λ§μ‘±νμ§ λͺ»ν΄ Preflightκ° λ°μνλ κ²½μ°κ° λ§λ€.
2. Preflight Request(μλΉ μμ²)
λ¨μ μμ²μ 쑰건μ λ§μ‘±νμ§ λͺ»ν κ²½μ°(μ: Content-Type: application/json λλ 컀μ€ν
ν€λ μ¬μ©), λΈλΌμ°μ λ μ€μ μμ²μ 보λ΄κΈ° μ μ μμ νμ§ νμΈνκΈ° μν΄ μλΉ μμ²μ λ¨Όμ 보λΈλ€.
λΈλΌμ°μ κ°
OPTIONSλ©μλλ‘ μμ² μ 보(Origin, Method, Header)λ₯Ό λ΄μ μλ²μ μ μ‘μλ²λ νμ© μ¬λΆλ₯Ό λ΄μ ν€λ(
Access-Control-Allow-*)μ ν¨κ» μλ΅λΈλΌμ°μ λ μλ² μλ΅μ νμΈνκ³ μμ νλ€κ³ νλ¨λλ©΄ μ€μ μμ²μ μ μ‘
λΈλΌμ°μ λ Preflight κ²°κ³Όλ₯Ό
Access-Control-Max-Ageμκ°λ§νΌ μΊμ±νμ¬ λ§€λ² μλΉ μμ²μ 보λ΄μ§ μλλ‘ μ΅μ ν
3. Credentialed Request (μΈμ¦ μ 보λ₯Ό ν¬ν¨ν μμ²)
ν΄λΌμ΄μΈνΈκ° μΏ ν€λ μΈμ¦ ν€λ(Authorization)λ₯Ό ν¬ν¨νμ¬ μμ²μ λ³΄λΌ λ λ°μνλ€.
ν΄λΌμ΄μΈνΈ μ€μ :
credentials: 'include'(fetch API) λλwithCredentials = true(axios/XHR) μ€μ νμμλ² μ€μ μ μ½ μ¬ν
Access-Control-Allow-Originμλ μμΌλμΉ΄λ(-)λ₯Ό μ¬μ©ν μ μμΌλ©°, λ°λμ ꡬ체μ μΈ Origin(μ:http://localhost:3000) λͺ μ νμAccess-Control-Allow-Credentials: trueν€λ μΆκ° νμ
μ£Όμ μλ΅ ν€λ
μλ²λ λ€μ ν€λλ€μ ν΅ν΄ CORS μ μ± μ λΈλΌμ°μ μ μλ¦°λ€.
Access-Control-Allow-Origin: μμ²μ νμ©ν μΆμ². λ¨μΌ λλ©μΈ λλ-Access-Control-Allow-Methods: νμ©ν HTTP λ©μλ (GET, POST, PUT, OPTIONS λ±)Access-Control-Allow-Headers: νμ©ν 컀μ€ν ν€λAccess-Control-Allow-Credentials: μΏ ν€ λ± μΈμ¦ μ 보 νμ© μ¬λΆAccess-Control-Max-Age: Preflight μμ²μ μΊμ μκ°(μ΄)
μ°Έκ³ μλ£
Last updated