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
Was this helpful?