CORS 정책

이 페이지는 Apigee 및 Apigee Hybrid에 적용됩니다.

Apigee Edge 문서 보기

대상

교차 출처 리소스 공유(CORS)는 웹페이지에서 실행되는 자바스크립트 XMLHttpRequest(XHR) 호출이 출처가 다른 도메인의 리소스와 상호작용할 수 있도록 허용하는 표준 메커니즘입니다. CORS는 모든 브라우저에서 적용되는 동일 출처 정책에 일반적으로 구현되는 솔루션입니다.

예를 들어 브라우저에서 실행되는 자바스크립트 코드에서 Twitter API로 XHR 호출을 수행하면 호출이 실패합니다. 이는 브라우저에 페이지를 제공하는 도메인이 Twitter API를 제공하는 도메인과 동일하지 않기 때문입니다. CORS는 이 문제를 해결하기 위해 서버가 교차 출처 리소스 공유를 제공하려는 경우 선택을 하도록 허용하는 솔루션을 제공합니다.

이 CORS 정책은 Apigee 고객이 웹 애플리케이션에서 사용되는 API에 대해 CORS 정책을 설정할 수 있게 해줍니다.

이 정책은 표준 정책이며 모든 환경 유형에 배포할 수 있습니다. 정책 유형과 각 환경 유형에서의 가용성에 대한 자세한 내용은 정책 유형을 참조하세요.

<CORS> 요소

CORS 정책을 정의합니다.

기본값 아래의 기본 정책 탭을 참조하세요.
필수 여부 필수
유형 복합 객체
상위 요소 해당 사항 없음
하위 요소 <AllowCredentials>
<AllowHeaders>
<AllowMethods>
<AllowOrigins>
<DisplayName>
<ExposeHeaders>
<GeneratePreflightResponse>
<IgnoreUnresolvedVariables>
<MaxAge>

<CORS> 요소는 다음 구문을 사용합니다.

구문

<CORS> 요소는 다음 구문을 사용합니다.


<CORS continueOnError="[false|true]" enabled="[false|true]" name="POLICY_NAME">
  <DisplayName>DISPLAY_NAME</DisplayName>
  <AllowOrigins>[{message template}|URL|URL, URL, ...|{context-variable}|{flow-variable}|*]</AllowOrigins>
  <AllowMethods>[GET, PUT, POST, DELETE, ...|*]</AllowMethods>
  <AllowHeaders>[origin, x-requested-with, accept, content-type, ...]</AllowHeaders>
  <ExposeHeaders>[X-CUSTOM-HEADER-A, X-CUSTOM-HEADER-B, ... | *]</ExposeHeaders>
  <MaxAge>[integer|-1]</MaxAge>
  <AllowCredentials>[false|true]</AllowCredentials>
  <GeneratePreflightResponse>[false|true]</GeneratePreflightResponse>
  <IgnoreUnresolvedVariables>[false|true]</IgnoreUnresolvedVariables>
</CORS>

기본 정책

다음 예시는 Edge UI에서 흐름에 CORS 정책을 추가할 때의 기본 설정을 보여줍니다.

<CORS continueOnError="false" enabled="true" name="add-cors">
    <DisplayName>Add CORS</DisplayName>
    <AllowOrigins>{request.header.origin}</AllowOrigins>
    <AllowMethods>GET, PUT, POST, DELETE</AllowMethods>
    <AllowHeaders>origin, x-requested-with, accept, content-type</AllowHeaders>
    <ExposeHeaders>*</ExposeHeaders>
    <MaxAge>3628800</MaxAge>
    <AllowCredentials>false</AllowCredentials>
    <GeneratePreflightResponse>true</GeneratePreflightResponse>
    <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
</CORS>

Apigee UI에서 새 CORS 정책을 삽입할 때 템플릿에는 모든 가능한 작업에 대한 스텁이 포함됩니다. 일반적으로 이 정책으로 수행할 작업을 선택하고 나머지 하위 요소를 삭제합니다. 예를 들어 리소스에 액세스하도록 허용되는 HTTP 메서드를 지정하려면 <AllowMethods> 요소를 사용하고 이를 더 읽기 가능하도록 정책에서 다른 하위 요소를 삭제합니다.

This element has the following attributes that are common to all policies:

Attribute Default Required? Description
name N/A Required

The internal name of the policy. The value of the name attribute can contain letters, numbers, spaces, hyphens, underscores, and periods. This value cannot exceed 255 characters.

Optionally, use the <DisplayName> element to label the policy in the management UI proxy editor with a different, natural-language name.

continueOnError false Optional Set to false to return an error when a policy fails. This is expected behavior for most policies. Set to true to have flow execution continue even after a policy fails. See also:
enabled true Optional Set to true to enforce the policy. Set to false to turn off the policy. The policy will not be enforced even if it remains attached to a flow.
async   false Deprecated This attribute is deprecated.

각 하위 요소는 다음 섹션에 설명되어 있습니다.

예시

다음 섹션에는 모든 하위 요소에 대한 예시가 제공되어 있습니다.

하위 요소 참조

이 섹션에서는 <CORS>의 하위 요소를 설명합니다.

<AllowCredentials>

사용자 인증 정보를 사용하여 호출자가 실제 요청(프리플라이트 아님)을 전송하도록 허용되는지 여부를 나타냅니다. Access-Control-Allow-Credentials 헤더로 변환됩니다.

기본값 지정하지 않으면 Access-Control-Allow-Credentials가 설정되지 않습니다.
필수 여부 선택사항
유형 불리언
상위 요소 <CORS>
하위 요소 없음

<AllowCredentials> 요소는 다음 문법을 사용합니다.

구문

<CORS continueOnError="[false|true]" enabled="[false|true]" name="POLICY_NAME">
  <AllowOrigins>[{message template}|URL|URL, URL, ...|{context-variable}|{flow-variable}|*]</AllowOrigins>
  <AllowCredentials>[false|true]</AllowCredentials>
</CORS>
      

예

This example sets the Access-Control-Allow-Credentials header to false. That is, the caller is not allowed to send the actual request (not the preflight) using credentials.

<CORS continueOnError="false" enabled="true" name="add-cors">
  <AllowOrigins>{request.header.origin}</AllowOrigins>
  <AllowCredentials>false</AllowCredentials>
</CORS>

<AllowHeaders>

리소스를 요청할 때 사용할 수 있는 HTTP 헤더 목록입니다. Access-Control-Allow-Headers 헤더로 직렬화됩니다.

기본값 Origin, Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers
필수 여부 선택사항
유형 문자열, 메시지 템플릿* 지원
상위 요소 <CORS>
하위 요소 없음

* 자세한 내용은 메시지 템플릿이란?을 참조하세요.

<AllowHeaders> 요소는 다음 구문을 사용합니다.

구문

<CORS continueOnError="[false|true]" enabled="[false|true]" name="POLICY_NAME">
  <AllowOrigins>[{message template}|URL|URL, URL, ...|{context-variable}|{flow-variable}|*]</AllowOrigins>
  <AllowHeaders>[origin, x-requested-with, accept, content-type, ...]</AllowHeaders>
</CORS>

예

CORS AllowOrigins 예시

이 예시에서는 리소스를 요청할 때 사용할 수 있는 HTTP 헤더를 지정합니다.

<CORS continueOnError="false" enabled="true" name="add-cors">
  <AllowOrigins>{request.header.origin}</AllowOrigins>
  <AllowHeaders>origin, x-requested-with, accept, content-type</AllowHeaders>
</CORS>

<AllowMethods>

리소스에 액세스하도록 허용된 HTTP 메서드 목록입니다. 콘텐츠는 Access-Control-Allow-Methods 헤더로 직렬화됩니다.

기본값 GET, POST, HEAD, OPTIONS
필수 여부 선택사항
유형 문자열, 메시지 템플릿* 지원
상위 요소 <CORS>
하위 요소 없음

* 자세한 내용은 메시지 템플릿이란?을 참조하세요.

<AllowMethods> 요소는 다음 구문을 사용합니다.

구문

<CORS continueOnError="[false|true]" enabled="[false|true]" name="POLICY_NAME">
  <AllowOrigins>[{message template}|URL|URL, URL, ...|{context-variable}|{flow-variable}|*]</AllowOrigins>
  <AllowMethods>[GET, PUT, POST, DELETE, ...|*]</AllowMethods>
</CORS>

예시:
목록

This example specifies the HTTP methods that are allowed to access the resource.

<CORS continueOnError="false" enabled="true" name="add-cors">
  <AllowOrigins>{request.header.origin}</AllowOrigins>
  <AllowMethods>GET, PUT, POST, DELETE</AllowMethods>
</CORS>

예시:
와일드 카드

This example specifies that all HTTP methods are allowed to access the resource.

<CORS continueOnError="false" enabled="true" name="add-cors">
  <AllowOrigins>{request.header.origin}</AllowOrigins>
  <AllowMethods>*</AllowMethods>
</CORS>

<AllowOrigins>

리소스에 액세스가 허용되는 원본 목록입니다. 별표(*)를 사용하여 원본에서 리소스에 액세스를 사용 설정합니다. 그렇지 않으면 쉼표로 구분된 원본 허용 목록을 제공합니다. 일치 항목을 찾았으면 클라이언트에서 제공된 대로 송신 Access-Control-Allow-Origin이 원본으로 설정됩니다.

기본값 해당 사항 없음
필수 여부 필수
유형 문자열, 메시지 템플릿* 지원
상위 요소 <CORS>
하위 요소 없음

* 자세한 내용은 메시지 템플릿이란?을 참조하세요.

<AllowOrigins> 요소는 다음 구문을 사용합니다.

구문

<CORS continueOnError="[false|true]" enabled="[false|true]" name="POLICY_NAME">
  <AllowOrigins>[{message template}|URL|URL, URL, ...|{context-variable}|{flow-variable}|*]</AllowOrigins>
</CORS>

예시:
단일 URL

이 예시에서는 리소스에 액세스할 수 있는 단일 URL 출처를 지정합니다.

<CORS continueOnError="false" enabled="true"< name="add-cors">
<  AllowOrigins&<gt;https://www.w3.org/AllowOrigins>
/CORS>

예시:
여러 URL

이 예시에서는 리소스에 액세스할 수 있는 여러 출처를 지정합니다.

<CORS continueOnError="false" enabled="true" name="add-cors">
  <AllowOrigins>https://www.w3.org, https://www.apache.org</AllowOrigins>
</CORS>

예시:
컨텍스트 변수

이 예시에서는 리소스에 액세스할 수 있는 하나 이상의 출처를 나타내는 컨텍스트 변수를 지정합니다.

<CORS continueOnError="false" enabled="true" name="add-cors">
  <AllowOrigins>{origins.list}</AllowOrigins>
</CORS>

예시:
흐름 변수

This example specifies a flow variable that represents one origin that is allowed to access the resource.

<CORS continueOnError="false" enabled="true" name="add-cors">
  <AllowOrigins>{request.header.origin}</AllowOrigins>
</CORS>

예시:
와일드 카드

이 예시에서는 모든 출처에서 리소스에 액세스할 수 있음을 허용됩니다.

<CORS continueOnError="false" enabled="true" name="add-cors">
  <AllowOrigins>*</AllowOrigins>
</CORS>

<DisplayName>

Use in addition to the name attribute to label the policy in the management UI proxy editor with a different, more natural-sounding name.

The <DisplayName> element is common to all policies.

Default Value N/A
Required? Optional. If you omit <DisplayName>, the value of the policy's name attribute is used.
Type String
Parent Element <PolicyElement>
Child Elements None

The <DisplayName> element uses the following syntax:

Syntax

<PolicyElement>
  <DisplayName>POLICY_DISPLAY_NAME</DisplayName>
  ...
</PolicyElement>

Example

<PolicyElement>
  <DisplayName>My Validation Policy</DisplayName>
</PolicyElement>

The <DisplayName> element has no attributes or child elements.

<ExposeHeaders>

브라우저가 액세스하도록 허용되는 HTTP 헤더 목록 또는 모든 HTTP 헤더를 허용하는 별표(*)입니다. Access-Control-Expose-Headers 헤더로 직렬화됩니다.

기본값 지정하지 않으면 Access-Control-Expose-Headers가 설정되지 않습니다. 단순하지 않은 헤더는 기본적으로 노출되지 않습니다.
필수 여부 선택사항
유형 문자열, 메시지 템플릿* 지원
상위 요소 <CORS>
하위 요소 없음

* 자세한 내용은 메시지 템플릿이란?을 참조하세요.

<ExposeHeaders> 요소는 다음 구문을 사용합니다.

구문

<CORS continueOnError="[false|true]" enabled="[false|true]" name="POLICY_NAME">
  <AllowOrigins>[{message template}|URL|URL, URL, ...|{context-variable}|{flow-variable}|*]</AllowOrigins>
  <ExposeHeaders>[X-CUSTOM-HEADER-A, X-CUSTOM-HEADER-B, ... | *]</ExposeHeaders>
</CORS>

예

This example specifies that the browsers are allowed to access all HTTP headers.

<CORS continueOnError="false" enabled="true" name="add-cors">
  <AllowOrigins>{request.header.origin}</AllowOrigins>
  <ExposeHeaders>*</ExposeHeaders>
</CORS>

<GeneratePreflightResponse>

정책이 CORS 프리플라이트 응답을 생성하고 반환해야 하는지 여부를 나타냅니다. false인 경우 응답이 전송되지 않습니다. 대신 다음 흐름 변수가 채워집니다.

  • cross_origin_resource_sharing.allow.credentials
  • cross_origin_resource_sharing.allow.headers
  • cross_origin_resource_sharing.allow.methods
  • cross_origin_resource_sharing.allow.origin
  • cross_origin_resource_sharing.allow.origins.list
  • cross_origin_resource_sharing.expose.headers
  • cross_origin_resource_sharing.max.age
  • cross_origin_resource_sharing.preflight.accepted
  • cross_origin_resource_sharing.request.headers
  • cross_origin_resource_sharing.request.method
  • cross_origin_resource_sharing.request.origin
  • cross_origin_resource_sharing.request.type
기본값 true
필수 여부 선택사항
유형 불리언
상위 요소 <CORS>
하위 요소 없음

<GeneratePreflightResponse> 요소는 다음 문법을 사용합니다.

구문

<CORS continueOnError="[false|true]" enabled="[false|true]" name="POLICY_NAME">
  <GeneratePreflightResponse>[false|true]</GeneratePreflightResponse>
  <GeneratePreflightResponse>[false|true]</GeneratePreflightResponse>
</CORS>

예

이 예시에서는 정책이 CORS 실행 전 응답을 생성하고 반환하도록 지정합니다.

<CORS continueOnError="false" enabled="true" name="add-cors">
  <AllowOrigins>{request.header.origin}</AllowOrigins>
  <GeneratePreflightResponse>true</GeneratePreflightResponse>
</CORS>

<IgnoreUnresolvedVariables>

해결되지 않은 변수가 발생하면 처리를 중지할지 여부를 결정합니다. 확인되지 않은 변수를 무시하고 계속 처리하려면 true로 설정합니다. 그렇지 않으면 false로 설정합니다.

기본값 true
필수 여부 선택사항
유형 불리언
상위 요소 <CORS>
하위 요소 없음

<IgnoreUnresolvedVariables> 요소는 다음 문법을 사용합니다.

구문

<CORS continueOnError="[false|true]" enabled="[false|true]" name="POLICY_NAME">
  <AllowOrigins>[{message template}|URL|URL, URL, ...|{context-variable}|{flow-variable}|*]</AllowOrigins>
  <IgnoreUnresolvedVariables>[false|true]</IgnoreUnresolvedVariables>
</CORS>

예

This example specifies that processing continues when an unresolved variable is encountered.

<CORS continueOnError="false" enabled="true" name="add-cors">
  <AllowOrigins>{request.header.origin}</AllowOrigins>
  <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
</CORS>

<MaxAge>

프리플라이트 요청의 결과가 캐시에 저장될 수 있는 기간(초)을 지정합니다. 값이 -1이면 Access-Control-Max-Age 헤더에 -1 값이 채워지고, 캐시가 사용 중지되어, 모든 호출에 대해 프리플라이트 OPTIONS 확인이 요구됩니다. 이것은 Access-Control-Max-Age 사양에 정의되어 있습니다.

기본값 1800
필수 여부 선택사항
유형 정수
상위 요소 <CORS>
하위 요소 없음

<MaxAge> 요소는 다음 문법을 사용합니다.

구문

<CORS continueOnError="[false|true]" enabled="[false|true]" name="POLICY_NAME">
  <AllowOrigins>[{message template}|URL|URL, URL, ...|{context-variable}|{flow-variable}|*]</AllowOrigins>
  <MaxAge>[integer|-1]</MaxAge>
</CORS>

예시:
캐시

This example specifies that the results of a preflight request can be cached for 3628800 seconds.

<CORS continueOnError="false" enabled="true" name="add-cors">
  <AllowOrigins>{request.header.origin}</AllowOrigins>
  <MaxAge>3628800</MaxAge>
</CORS>

예시:
캐시 없음

이 예시에서는 실행 전 요청의 결과를 캐시할 수 없음을 지정합니다.

<CORS continueOnError="false" enabled="true" name="add-cors">
  <AllowOrigins>{request.header.origin}</AllowOrigins>
  <MaxAge>-1</MaxAge>
</CORS>

사용 참고사항

OPTIONS 요청

CORS 정책에서 OPTIONS 요청을 수신하고 처리하면 프록시 흐름 실행이 프록시 응답 PreFlow로 직접 전달되어 요청 흐름을 완전히 건너뛰고 거기에서 실행을 계속합니다. 프록시 요청 흐름에서 OPTIONS 요청을 무시하는 조건을 만들 필요가 없습니다.

후속 호출에서 CORS 정책이 실행될 때 정책에 설정된 MaxAge가 만료되지 않은 경우 흐름은 정상적으로 계속됩니다. '응답이 클라이언트에 전송됨' 직전의 최종 응답 흐름에서 특수한 CORS 실행 단계인 'CORSResponseOrErrorFlowExecution'이 CORS 검증을 거친 응답을 반환하도록 CORS 응답 헤더(Access-Control-Allow-Credentials .Access-Control-Allow-Origin, Access-Control-Expose-Headers)를 설정합니다.

오류 코드

This section describes the fault codes and error messages that are returned and fault variables that are set by Apigee when this policy triggers an error. This information is important to know if you are developing fault rules to handle faults. To learn more, see What you need to know about policy errors and Handling faults.

Runtime errors

These errors can occur when the policy executes.

Fault code HTTP status Cause
steps.cors.UnresolvedVariable 500 This error occurs if a variable specified in the CORS policy is either:
  • Out of scope (not available in the specific flow where the policy is being executed)
  • or

  • Can't be resolved (is not defined)

Deployment errors

These errors can occur when you deploy a proxy containing this policy.

Error name Cause
InvalidMaxAge MaxAge is not number
MissingAllowOrigins AllowOrigins is not specified
InvalidHTTPMethods One of the methods in AllowMethods is not valid
AllowHeadersSizeTooLarge The string size in AllowHeaders is too large.
ExposeHeadersSizeTooLarge The string size in ExposeHeaders is too large.

Fault variables

These variables are set when this policy triggers an error at runtime. For more information, see What you need to know about policy errors.

Variables Where Example
fault.name = "FAULT_NAME" FAULT_NAME is the name of the fault, as listed in the Runtime errors table above. The fault name is the last part of the fault code. fault.name Matches "UnresolveVariable"
cors.POLICY_NAME.failed POLICY_NAME is the user-specified name of the policy that threw the fault. cors.AddCORS.failed = true

Example error response

{
   "fault":{
      "detail":{
         "errorcode":"steps.cors.UnresolvedVariable"
      },
      "faultstring":"CORS[AddCORS]: unable to resolve variable wrong.var"
   }
}

Example fault rule

<FaultRule name="Add CORS Fault">
    <Step>
        <Name>Add-CORSCustomUnresolvedVariableErrorResponse</Name>
        <Condition>(fault.name Matches "UnresolvedVariable") </Condition>
    </Step>
    <Condition>(cors.Add-CORS.failed = true) </Condition>
</FaultRule>

흐름 변수

CorsFlowInfo FlowInfo 객체가 추가되고 trace하도록 제공됩니다.

속성 유형 읽기/쓰기 설명 범위 시작
cross_origin_resource_sharing.allow.credentials 불리언 읽기/쓰기 <AllowCredentials>의 값 프록시 요청
cross_origin_resource_sharing.allow.headers 문자열 읽기/쓰기 <AllowHeaders>의 값 프록시 요청
cross_origin_resource_sharing.allow.methods 문자열 읽기/쓰기 <AllowMethods>의 값 프록시 요청
cross_origin_resource_sharing.allow.origin 문자열 읽기/쓰기 허용되는 요청 원본이며, 허용 목록에 없으면 비어 있습니다. 프록시 요청
cross_origin_resource_sharing.allow.origins.list 문자열 읽기/쓰기 <AllowOrigins>의 값 프록시 요청
cross_origin_resource_sharing.expose.headers 문자열 읽기/쓰기 <ExposeHeaders>의 값 프록시 요청
cross_origin_resource_sharing.max.age 정수 읽기/쓰기 <MaxAge>의 값 프록시 요청
cross_origin_resource_sharing.preflight.accepted 불리언 읽기/쓰기 프리플라이트 요청이 수락되었는지 여부를 나타냅니다. 프록시 요청
cross_origin_resource_sharing.request.headers 문자열 읽기/쓰기 요청 Access-Control-Request-Headers 헤더 값 프록시 요청
cross_origin_resource_sharing.request.method 문자열 읽기/쓰기 요청 Access-Control-Request-Method 헤더 값 프록시 요청
cross_origin_resource_sharing.request.origin 문자열 읽기/쓰기 request.header.origin와 동일 프록시 요청
cross_origin_resource_sharing.request.type 문자열 읽기/쓰기

CORS 요청의 유형입니다. 가능한 값은 다음과 같습니다.

  • ACTUAL: 프리플라이트 요청이 아닌 요청
  • PRE_FLIGHT: 프리플라이트 요청
프록시 요청