๐Ÿ“‹ Project

[CORS] CORS๋ž€? CORS ์—๋Ÿฌ ํ•ด๊ฒฐ!

sun_young 2024. 6. 30. 21:39

๐Ÿ”Ž CORS๋ž€?

Cross-Origin Resource Sharing, ์ฆ‰ ๊ต์ฐจ ์ถœ์ฒ˜ ๋ฆฌ์†Œ์Šค ๊ณต์œ  ์ •์ฑ…์œผ๋กœ ์—‡๊ฐˆ๋ฆฐ ๋‹ค๋ฅธ ์ถœ์ฒ˜๋ฅผ ์˜๋ฏธํ•œ๋‹ค

 

  • ์ถœ์ฒ˜(Origin)๋ž€? 
    • ์šฐ๋ฆฌ๊ฐ€ ์–ด๋–ค ์‚ฌ์ดํŠธ๋ฅผ ์ ‘์†ํ•  ๋•Œ ์ธํ„ฐ๋„ท ์ฃผ์†Œ์ฐฝ์— URL์„ ํ†ตํ•ด ์ ‘๊ทผํ•˜๊ฒŒ ๋œ๋‹ค. URL์€ ์—ฌ๋Ÿฌ ๊ฐœ์˜ ๊ตฌ์„ฑ ์š”์†Œ๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ๋Š”๋ฐ ์ถœ์ฒ˜๋Š” ํ”„๋กœํ† ์ฝœ๊ณผ ํ˜ธ์ŠคํŠธ, ํฌํŠธ๊นŒ์ง€ ๋ชจ๋‘ ํ•ฉ์นœ URL์„ ์˜๋ฏธํ•œ๋‹ค๊ณ  ๋ณด๋ฉด ๋œ๋‹ค
  • ๋™์ผ ์ถœ์ฒ˜ ์ •์ฑ…(Same-Origin Policy)
    • ๋™์ผํ•œ ์ถœ์ฒ˜์— ๋Œ€ํ•ด์„œ๋งŒ ๋ฆฌ์†Œ์Šค๋ฅผ ๊ณต์œ ํ•  ์ˆ˜ ์žˆ๋‹ค๋Š” ์ •์ฑ…์„ ๊ฐ€์ง€๊ณ  ์žˆ๋‹ค → ๋‹ค๋ฅธ ์ถœ์ฒ˜ ์„œ๋ฒ„์— ์žˆ๋Š” ๋ฆฌ์†Œ์Šค๋Š” ์ƒํ˜ธ์ž‘์šฉ์ด ๋ถˆ๊ฐ€๋Šฅํ•˜๋‹ค (์•…์˜์ ์ธ ๊ฒฝ์šฐ๋ฅผ ๋ฐฉ์ง€ํ•˜๊ธฐ ์œ„ํ•ด)
  • ๊ฐ™์€ ์ถœ์ฒ˜์™€ ๋‹ค๋ฅธ ์ถœ์ฒ˜ ๊ตฌ๋ถ„์€ ์–ด๋–ป๊ฒŒ?
    • URL์˜ ๊ตฌ์„ฑ ์š”์†Œ ์ค‘ ํ”„๋กœํ† ์ฝœ, ํ˜ธ์ŠคํŠธ, ํฌํŠธ ์ด 3๊ฐ€์ง€๋งŒ ๋™์ผํ•˜๋‹ค๋ฉด ๋™์ผ ์ถœ์ฒ˜๋กœ ํŒ๋‹จ!
๋”๋ณด๊ธฐ

 

๐Ÿ”Ž ์˜ค๋ฅ˜ ํ•ด๊ฒฐ ๋ฐฉ์•ˆ

์šฐ๋ฆฌ ํ”„๋กœ์ ํŠธ๋Š” MSA ๊ตฌ์กฐ๋ฅผ ๊ฐ–๊ณ  ์žˆ๊ธฐ ๋•Œ๋ฌธ์— ๊ฒŒ์ดํŠธ์›จ์ด ์„œ๋น„์Šค์˜ application.yml ํŒŒ์ผ์— cors ์„ค์ •์„ ์ถ”๊ฐ€ํ•˜์˜€๋‹ค

 gateway:
      globalcors:
        corsConfigurations:
          '[/**]':
            allowedOrigins:
              - "http://localhost:3000"
            allow-credentials: true
            allowedHeaders:
              - x-requested-with
              - authorization
              - content-type
              - credential
              - X-AUTH-TOKEN
              - X-CSRF-TOKEN
            allowedMethods:
              - POST
              - GET
              - PUT
              - PATCH
              - OPTIONS
              - DELETE
            exposed-headers:
              - Authorization

 

๐Ÿ“ข allow-credentials๋ฅผ true๋กœ ์„ค์ •ํ•˜๋ฉด allowedOrigins๋Š” "*"๋กœ ์„ค์ •๋  ์ˆ˜ ์—†๋‹ค

 

  • allowedHeaders : ํด๋ผ์ด์–ธํŠธ ์ธก์˜ CORS ์š”์ฒญ์— ํ—ˆ์šฉ๋˜๋Š” ํ—ค๋” ์ง€์ •
    • ํ˜„์žฌ ์šฐ๋ฆฌ ํ”„๋กœ์ ํŠธ์—์„œ๋Š” JWT ํ† ํฐ์„ header์— ๋‹ด์•„์„œ ํด๋ผ์ด์–ธํŠธ ์ธก์œผ๋กœ ๋ณด๋‚ด๊ณ  ์žˆ๋‹ค. ๋”ฐ๋ผ์„œ allowedHeaders ์„ค์ •๋„ ์ถ”๊ฐ€ํ•ด์•ผ 403 ์˜ค๋ฅ˜๊ฐ€ ์•ˆ ๋œฌ๋‹ค
  • exposed-headers : ํด๋ผ์ด์–ธํŠธ๊ฐ€ ์‘๋‹ต์— ์ ‘๊ทผํ•  ์ˆ˜ ์žˆ๋Š” ํ—ค๋” ์ง€์ •
    • ๊ฐœ๋ฐœ์ž ๋„๊ตฌ - ๋„คํŠธ์›Œํฌ ํƒญ์— ์žˆ๋Š” ๋ฐ์ดํ„ฐ๋Š” ์ •๋ณด๋ฅผ ์ฝ์„ ์ˆ˜๋งŒ ์žˆ๋‹ค. ํด๋ผ์ด์–ธํŠธ์—์„œ ์„œ๋ฒ„์—์„œ ๋„˜์–ด์˜จ ๋ฐ์ดํ„ฐ์— ์ ‘๊ทผํ•˜๊ธฐ ์œ„ํ•ด์„œ๋Š” exposed-headers ์„ค์ •์„ ์ถ”๊ฐ€ํ•ด์•ผ ํ•œ๋‹ค.