Post

CORS

교차 출처 요청을 제어하는 웹 보안 정책 (Kotlin 기반 예시 포함)

개념 설명:

Cross-Origin Resource Sharing (CORS) is an HTTP-header based mechanism that allows a server to indicate any origins (domain, scheme, or port) other than its own from which a browser should permit loading resources. CORS also relies on a mechanism by which browsers make a “preflight” request to the server hosting the cross-origin resource, in order to check that the server will permit the actual request.
공식문서 (MDN)
CORS는 브라우저에서 다른 출처(origin)의 리소스 요청을 허용할지를 결정하는 보안 기능.
동일 출처 정책(Same-Origin Policy)에 따라 브라우저는 기본적으로 cross-origin HTTP 요청을 제한하며, 이를 우회할 수 있도록 서버 측에서 명시적으로 허용해야 함.

  • 비슷한 개념과 비교:
    • Same-Origin Policy (SOP): 기본적으로 적용되는 브라우저 보안 정책으로, origin이 다르면 접근 차단.
    • JSONP: 스크립트 태그를 이용한 과거 방식으로, CORS의 보안 대안으로 더 이상 권장되지 않음.
  • 사용이 적합한 환경:
    • 프론트엔드와 백엔드가 서로 다른 도메인, 포트, 프로토콜을 사용하는 구조
    • 예: Next.js + Spring Boot 백엔드 API 서버
    • 외부 API 호출, 마이크로서비스 간 통신에서도 사용됨
  • 사용 방법:

    Kotlin(Spring Boot) 기반 CORS 설정 예시

    1. 글로벌 설정 (WebMvcConfigurer 사용)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    
    import org.springframework.context.annotation.Configuration
    import org.springframework.web.servlet.config.annotation.CorsRegistry
    import org.springframework.web.servlet.config.annotation.WebMvcConfigurer
    
    @Configuration
    class WebConfig : WebMvcConfigurer {
        override fun addCorsMappings(registry: CorsRegistry) {
            registry.addMapping("/api/**")
                .allowedOrigins("https://enginrect.com")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowCredentials(true)
        }
    }
    

    2. 개별 컨트롤러에 적용

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    
    import org.springframework.web.bind.annotation.*
    
    @RestController
    @RequestMapping("/api")
    @CrossOrigin(origins = ["https://enginrect.com"])
    class ApiController {
    
        @GetMapping("/data")
        fun getData(): Map<String, String> {
            return mapOf("message" to "Hello from enginrect.com!")
        }
    }
    

    Preflight 요청 처리

    • Spring Boot는 OPTIONS 메서드에 대한 preflight 요청을 자동으로 감지하고 응답함.
    • 추가 커스터마이징이 필요한 경우 CorsFilter를 별도로 구현 가능.
  • 참고 사항:
    • 서버가 CORS 설정을 하지 않으면 브라우저에서 자동으로 차단됨.
    • 로컬 개발 시에는 localhostallowedOrigins에 포함시키거나, 프론트엔드에서 proxy를 설정해 우회 가능.
  • AWS에서의 CORS 설정


    AWS에서는 다양한 서비스에서 CORS를 별도로 설정 필요. 대표적인 예로 S3, API Gateway, CloudFront.

1. Amazon S3

  • S3 버킷에 저장된 리소스에 외부 도메인이 접근하려면 CORS 정책을 설정 필요.
  • S3 콘솔 > 버킷 > 권한 > CORS 설정에 JSON 형식으로 입력.
1
2
3
4
5
6
7
8
9
[
  {
    "AllowedHeaders": ["*"],
    "AllowedMethods": ["GET", "POST"],
    "AllowedOrigins": ["https://enginrect.com"],
    "ExposeHeaders": [],
    "MaxAgeSeconds": 3000
  }
]

2. Amazon API Gateway

  • API Gateway 리소스는 CORS 설정을 명시적으로 해주어야 함.
  • 콘솔에서 각 리소스 선택 후 Enable CORS 버튼 클릭하면 자동으로 OPTIONS 메서드와 헤더가 추가됨.
  • Lambda를 백엔드로 사용할 경우, 응답 본문에서 CORS 헤더를 포함해야 함:
1
2
3
4
5
6
7
8
{
  "statusCode": 200,
  "headers": {
    "Access-Control-Allow-Origin": "https://enginrect.com",
    "Access-Control-Allow-Methods": "GET,POST,OPTIONS"
  },
  "body": "{...}"
}

3. AWS CloudFront

  • CloudFront는 자체적으로 CORS를 제어하지 않으며, 오리진에서 전달된 헤더를 전달함.
  • 필요한 경우 응답 헤더 정책(Origin Response Headers Policy)을 설정하여 CORS 헤더를 추가 가능.
  • 예: S3 오리진에 대해 Access-Control-Allow-Origin을 자동 삽입하도록 설정 가능.

AWS 공식문서 참고:

This post is licensed under CC BY 4.0 by the author.