VerifyAPIKey 정책

현재 Apigee Edge 문서가 표시되고 있습니다.
Apigee X 문서로 이동
정보

내용

API 키 검증 정책을 사용하면 런타임에 API 키 확인을 시행하여 승인된 API 키가 있는 앱만 API에 액세스할 수 있습니다. 이 정책은 API 키가 유효하고 취소되지 않았으며 API 제품과 연결된 특정 리소스를 사용하도록 승인되었습니다.

샘플

쿼리 매개변수의 키

<VerifyAPIKey name="APIKeyVerifier">
    <APIKey ref="request.queryparam.apikey" />
</VerifyAPIKey>

이 예시에서 정책은 request.queryparam.apikey라는 흐름 변수에서 API 키를 찾아야 합니다. request.queryparam.{name} 변수는 클라이언트 요청에서 전달된 쿼리 매개변수의 값으로 채워진 표준 Edge 흐름 변수입니다.

다음 curl 명령어는 쿼리 매개변수에서 API 키를 전달합니다.

curl http://myorg-test.apigee.net/mocktarget?apikey=IEYRtW2cb7A5Gs54A1wKElECBL65GVls

헤더의 키

<VerifyAPIKey name="APIKeyVerifier">
    <APIKey ref="request.header.x-apikey" />
</VerifyAPIKey>

이 예시에서 정책은 request.header.x-apikey라는 흐름 변수에서 API 키를 찾아야 합니다. request.header.{name} 변수는 클라이언트 요청에서 전달된 헤더 값으로 채워진 표준 Edge 흐름 변수입니다.

다음 cURL은 헤더에 API 키를 전달하는 방법을 보여줍니다.

curl "http://myorg-test.apigee.net/mocktarget" -H "x-apikey:IEYRtW2cb7A5Gs54A1wKElECBL65GVls"

변수의 키

<VerifyAPIKey name="APIKeyVerifier">
    <APIKey ref="requestAPIKey.key"/>
</VerifyAPIKey>

정책은 키가 포함된 변수를 참조할 수 있습니다. 이 예시에서 정책은 requestAPIKey.key라는 변수에서 API 키를 추출합니다.

이 변수는 자동으로 채워지는 방식입니다. 예를 들어 다음과 같이 변수 추출 정책을 사용하여 myKey라는 쿼리 매개변수에서 requestAPIKey.key를 채울 수 있습니다.

<ExtractVariables async="false" continueOnError="false" enabled="true" name="SetAPIKeyVar">
    <Source>request</Source>
    <QueryParam name="myKey">
        <Pattern ignoreCase="true">{key}</Pattern>
    </QueryParam>
    <VariablePrefix>requestAPIKey</VariablePrefix>
    <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
</ExtractVariables>

액세스 정책 흐름 변수

<AssignMessage async="false" continueOnError="false" enabled="true" name="accessverifyvars">
    <AssignVariable>
        <Name>devFirstName</Name>
        <Ref>verifyapikey.verify-api-key.developer.firstName</Ref>
        <Value>ErrorOnCopy</Value>
    </AssignVariable>
    <AssignVariable>
        <Name>devLastName</Name>
        <Ref>verifyapikey.verify-api-key.developer.lastName</Ref>
        <Value>ErrorOnCopy</Value>
    </AssignVariable>
    <AssignVariable>
        <Name>devEmail</Name>
        <Ref>verifyapikey.verify-api-key.developer.email</Ref>
        <Value>ErrorOnCopy</Value>
    </AssignVariable>
    <IgnoreUnresolvedVariables>true</IgnoreUnresolvedVariables>
    <AssignTo createNew="false" transport="http" type="request"/>
</AssignMessage>

Edge는 유효한 API 키에 대해 API 키 확인 정책을 실행할 때 흐름 변수 집합을 자동으로 채웁니다. 이러한 변수를 사용하여 앱 이름, 앱 ID, 앱을 등록한 개발자 또는 회사에 대한 정보에 액세스할 수 있습니다. 위의 예시에서 API 키 확인을 실행한 후 메시지 할당 정책을 사용하여 개발자의 이름, 성, 이메일 주소에 액세스할 수 있습니다.

이러한 변수에는 다음 프리픽스가 붙습니다.

verifyapikey.{policy_name}

이 예시에서 API 키 검증 정책 이름은 'verify-api-key'입니다. 따라서 verifyapikey.verify-api-key.developer.firstName. 변수에 액세스하여 요청을 수행하는 개발자의 이름을 참조해야 합니다.

알아보기


API 키 검증 정책 정보

개발자가 Edge에 앱을 등록하면 Edge에서 자동으로 고객 키와 비밀번호 쌍을 생성합니다. Edge UI에서 앱의 고객 키와 비밀번호 쌍을 확인하거나 Edge API에서 액세스할 수 있습니다.

앱 등록 시 개발자는 하나 이상의 API 제품을 선택하여 앱에 연결합니다. 여기서 API 제품은 API 프록시를 통해 액세스할 수 있는 리소스 모음입니다. 그런 다음 개발자는 앱과 관련된 API 제품의 API에 대한 모든 요청 중에 API 키 (고객 키)를 전달합니다. 자세한 내용은 게시 개요를 참조하세요.

API 키를 인증 토큰으로 사용하거나 OAuth 액세스 토큰을 얻는 데 사용할 수 있습니다. OAuth에서는 API 키를 '클라이언트 ID'라고 합니다. 이름은 서로 바꿔서 사용할 수 있습니다. 자세한 내용은 OAuth 홈을 참조하세요.

Edge는 API 키 확인 정책을 실행할 때 흐름 변수 집합을 자동으로 채웁니다. 자세한 내용은 아래의 흐름 변수를 참조하세요.

요소 참조

이 정책에 구성할 수 있는 요소와 속성은 다음과 같습니다.

<VerifyAPIKey async="false" continueOnError="false" enabled="true" name="Verify-API-Key-1">
    <DisplayName>Custom label used in UI</DisplayName>
    <APIKey ref="variable_containing_api_key"/>
</VerifyAPIKey>

<VerifyAPIKey> 속성

다음 예시는 <VerifyAPIKey> 태그의 속성을 보여줍니다.

<VerifyAPIKey async="false" continueOnError="false" enabled="true" name="Verify-API-Key-1">

다음 표는 모든 정책 상위 요소의 공통 속성에 대해 설명합니다.

속성 설명 기본 계정 현재 상태
name

정책의 내부 이름입니다. name 속성의 값에는 문자, 숫자, 공백, 하이픈, 밑줄, 마침표가 포함될 수 있습니다. 이 값은 255자(영문 기준)를 초과할 수 없습니다.

원하는 경우 <DisplayName> 요소를 사용하여 관리 UI 프록시 편집기의 정책에 다른 자연어 이름을 사용하여 정책에 라벨을 지정합니다.

N/A 필수
continueOnError

정책이 실패할 경우 오류가 반환되도록 하려면 false로 설정합니다. 이는 대부분의 정책에서 예상되는 동작입니다.

정책이 실패해도 흐름 실행이 계속되도록 하려면 true로 설정합니다.

false 선택사항
enabled

정책을 시행하려면 true로 설정합니다.

정책을 중지하려면 false로 설정합니다. 정책이 흐름에 연결되어 있어도 정책이 시행되지 않습니다.

true 선택사항
async

이 속성은 지원이 중단되었습니다.

false 지원 중단됨

<DisplayName> 요소

name 속성 외에도 이 요소를 사용하여 관리 UI 프록시 편집기의 정책에 다른 자연어 이름으로 라벨을 지정합니다.

<DisplayName>Policy Display Name</DisplayName>
기본 계정

N/A

이 요소를 생략하면 정책 name 속성 값이 사용됩니다.

현재 상태 선택사항
유형 문자열

<APIKey> 요소

이 요소는 API 키가 포함된 흐름 변수를 지정합니다. 일반적으로 클라이언트는 쿼리 매개변수, HTTP 헤더, 양식 매개변수로 API 키를 보냅니다. 예를 들어 키가 x-apikey라는 헤더로 전송되면 키는 변수 request.header.x-apikey에서 찾을 수 있습니다.

기본 계정 북미
Presence 필수
유형 문자열

특성

다음 표에서는 <APIKey> 요소의 속성을 설명합니다.

속성 설명 기본 계정 현재 상태
ref

API 키가 포함된 변수에 대한 참조입니다. 정책당 하나의 위치만 허용됩니다.

N/A 필수

이 예시에서는 키가 매개변수와 x-apikey라는 헤더에 전달됩니다.

쿼리 매개변수:

<VerifyAPIKey name="APIKeyVerifier">
    <APIKey ref="request.queryparam.x-apikey"/>
</VerifyAPIKey>

HTTP 헤더:

<VerifyAPIKey name="APIKeyVerifier">
    <APIKey ref="request.header.x-apikey"/>
</VerifyAPIKey>

HTTP 양식 매개변수:

<VerifyAPIKey name="APIKeyVerifier">
    <APIKey ref="request.formparam.x-apikey"/>
</VerifyAPIKey>

스키마

흐름 변수

유효한 API 키에 API 키 확인 정책이 적용되면 Edge는 흐름 변수 집합을 채웁니다. 이러한 변수는 흐름 후반에 실행되는 정책 또는 코드에 사용할 수 있으며 앱 이름, 키 승인에 사용되는 API 제품 또는 API의 커스텀 속성을 기반으로 커스텀 처리를 수행하는 데 자주 사용됩니다.

정책은 다음과 같은 여러 유형의 흐름 변수를 채웁니다.

  • 일반
  • 개발자
  • 회사
  • 분석

흐름 변수 유형마다 프리픽스가 다릅니다. 모든 변수는 배열로 특별히 지정된 변수를 제외하고 스칼라입니다.

일반 흐름 변수

다음 표에는 API 키 검증 정책으로 채운 일반적인 흐름 변수가 나와 있습니다. 이러한 변수에는 다음 프리픽스가 붙습니다.

verifyapikey.{policy_name}

예: verifyapikey.{policy_name}.client_id

사용 가능한 변수는 다음과 같습니다.

변수 설명
client_id 요청한 앱에서 제공하는 고객 키(API 키 또는 앱 키라고도 함)입니다.
client_secret 고객 키와 연결된 고객 보안 비밀입니다.
redirection_uris 요청의 모든 리디렉션 URI입니다.
developer.app.id

요청을 실행하는 개발자 앱의 ID입니다.

developer.app.name 요청을 보내는 개발자 앱의 앱 이름입니다.
developer.id

요청 앱의 소유자로 등록된 개발자의 ID입니다.

developer.{custom_attrib_name} 앱 키 프로필에서 파생된 모든 커스텀 속성입니다.
DisplayName 정책의 <DisplayName> 속성 값입니다.
failed API 키 검증이 실패하면 'true'로 설정됩니다.
{custom_app_attrib} 앱 프로필에서 파생된 모든 커스텀 속성입니다. 커스텀 속성의 이름을 지정합니다.
apiproduct.name* 요청 유효성을 검사하는 데 사용되는 API 제품의 이름입니다.
apiproduct.{custom_attrib_name}* API 제품 프로필에서 파생된 모든 커스텀 속성입니다.
apiproduct.developer.quota.limit* API 제품에 설정된 할당량 한도입니다(있는 경우).
apiproduct.developer.quota.interval* API 제품에 설정된 할당량 간격입니다(있는 경우).
apiproduct.developer.quota.timeunit* API 제품에 설정된 할당량 시간 단위입니다(있는 경우).
* API 제품이 유효한 환경, 프록시, 리소스 (proxy.pathsuffix에서 파생됨)로 구성된 경우 API 제품 변수가 자동으로 채워집니다. API 제품 설정에 대한 안내는 Edge 관리 API를 사용하여 API 게시를 참조하세요.

앱 흐름 변수

앱에 대한 정보가 포함된 다음 흐름 변수는 정책으로 채워집니다. 이러한 변수에는 다음 프리픽스가 붙습니다.

verifyapikey.{policy_name}.app.

예를 들면 다음과 같습니다.

verifyapikey.{policy_name}.app.name

사용 가능한 변수는 다음과 같습니다.

변수 설명
name 애플리케이션의 이름입니다.
id 앱의 ID입니다.
accessType Apigee에서 사용하지 않습니다.
callbackUrl 앱의 콜백 URL입니다. 일반적으로 OAuth에만 사용됩니다.
DisplayName 앱의 표시 이름입니다.
status 앱 상태입니다(예: '승인됨' 또는 '취소됨').
apiproducts 앱과 연결된 API 제품의 목록이 포함된 배열입니다.
appFamily 앱 또는 '기본값'이 포함된 앱 제품군입니다.
appParentStatus 앱 상위 요소의 상태(예: '활성' 또는 '비활성')
appType 앱 유형으로, '회사' 또는 '개발자'입니다.
appParentId 상위 앱의 ID입니다.
created_at 앱이 생성된 날짜/시간 스탬프입니다.
created_by 앱을 만든 개발자의 이메일 주소입니다.
last_modified_at 앱이 마지막으로 업데이트된 날짜/시간 스탬프입니다.
last_modified_by 마지막으로 앱을 업데이트한 개발자의 이메일 주소입니다.
{app_custom_attributes} 모든 커스텀 앱 속성입니다. 커스텀 속성의 이름을 지정합니다.

개발자 흐름 변수

개발자에 대한 정보가 포함된 다음 흐름 변수는 정책으로 채워집니다. 이러한 변수에는 다음 프리픽스가 붙습니다.

verifyapikey.{policy_name}.developer

예를 들면 다음과 같습니다.

verifyapikey.{policy_name}.developer.id

사용 가능한 변수는 다음과 같습니다.

변수 설명
id {org_name}@@@{developer_id} 반환
userName 개발자의 사용자 이름입니다.
firstName 개발자의 이름입니다.
lastName 개발자의 성
email 개발자의 이메일 주소
status 개발자 상태(active, inactive 또는 login_lock)
apps 개발자와 연결된 앱의 배열입니다.
created_at 개발자가 생성된 날짜/시간 스탬프입니다.
created_by 개발자를 만든 사용자의 이메일 주소입니다.
last_modified_at 개발자가 마지막으로 수정된 날짜/시간 스탬프입니다.
last_modified_by 개발자를 수정한 사용자의 이메일 주소입니다.
{developer_custom_attributes} 모든 커스텀 개발자 속성입니다. 커스텀 속성의 이름을 지정합니다.
Company 개발자와 연결된 회사의 이름입니다(있는 경우).

회사 흐름 변수

회사 정보가 포함된 다음 흐름 변수는 정책에서 채웁니다. 이러한 변수에는 다음 프리픽스가 붙습니다.

verifyapikey.{policy_name}.company

예를 들면 다음과 같습니다.

verifyapikey.{policy_name}.company.name

사용 가능한 변수는 다음과 같습니다.

변수 설명
name 회사 이름입니다.
displayName 회사의 표시 이름입니다.
id

회사 ID입니다.

apps 회사 앱 목록이 포함된 배열입니다.
appOwnerStatus
앱 소유자의 상태(활성, 비활성, login_lock)입니다.
created_at 회사가 생성된 날짜/시간 스탬프입니다.
created_by 회사를 만든 사용자의 이메일 주소입니다.
last_modified_at 회사가 마지막으로 수정된 날짜/시간 스탬프입니다.
last_modified_by 회사를 마지막으로 수정한 사용자의 이메일 주소입니다.
{company_custom_attributes} 모든 커스텀 회사 속성 커스텀 속성의 이름을 지정합니다.

분석 변수

다음 변수는 유효한 API 키에 대해 API 키 검증 정책이 시행되면 애널리틱스에서 자동으로 채워집니다. 이러한 변수는 API 키 검증 정책 및 OAuth 정책으로만 채웁니다.

변수와 값을 측정기준으로 사용하여 개발자 및 앱의 사용 패턴을 파악할 수 있습니다.

  • apiproduct.name
  • developer.app.name
  • client_id
  • developer.id

오류 참조

This section describes the fault codes and error messages that are returned and fault variables that are set by Edge 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
keymanagement.service.CompanyStatusNotActive 401 The Company associated with the Developer App that has the API key you are using has an inactive status. When a Company's status is set to inactive, you cannot access the developers or apps associated with that Company. An org admin can change a Company's status using the management API. See Set the Status of a Company.
keymanagement.service.DeveloperStatusNotActive 401

The developer who created the Developer App that has the API key you are using has an inactive status. When an App Developer's status is set to inactive, any Developer Apps created by that developer are deactivated. An admin user with appropriate permissions (such as Organization Administrator) can change a developer's status in the following ways:

keymanagement.service.invalid_client-app_not_approved 401 The Developer App associated with the API key is revoked. A revoked app cannot access any API products and cannot invoke any API managed by Apigee Edge. An org admin can change the status of a Developer App using the management API. See Approve or Revoke Developer App.
oauth.v2.FailedToResolveAPIKey 401 The policy expects to find the API key in a variable that is specified in the policy's <APIKey> element. This error arises when the expected variable does not exist (it cannot be resolved).
oauth.v2.InvalidApiKey 401 An API key was received by Edge, but it is invalid. When Edge looks up the key in its database, it must exactly match the on that was sent in the request. If the API worked previously, make sure the key was not regenerated. If the key was regenerated, you will see this error if you try to use the old key. For details, see Register apps and manage API keys.
oauth.v2.InvalidApiKeyForGivenResource 401 An API key was received by Edge, and it is valid; however, it does not match an approved key in the Developer App associated with your API proxy through a Product.

Deployment errors

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

Error name Cause
SpecifyValueOrRefApiKey The <APIKey> element does not have a value or key specified.

Fault variables

These variables are set when a runtime error occurs. 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 "FailedToResolveAPIKey"
oauthV2.policy_name.failed policy_name is the user-specified name of the policy that threw the fault. oauthV2.VK-VerifyAPIKey.failed = true

Example error responses

{  
   "fault":{  
      "faultstring":"Invalid ApiKey",
      "detail":{  
         "errorcode":"oauth.v2.InvalidApiKey"
      }
   }
}
{  
   "fault":{  
      "detail":{  
         "errorcode":"keymanagement.service.DeveloperStatusNotActive"
      },
      "faultstring":"Developer Status is not Active"
   }
}

Example fault rule

<FaultRule name="FailedToResolveAPIKey">
    <Step>
        <Name>AM-FailedToResolveAPIKey</Name>
    </Step>
    <Condition>(fault.name Matches "FailedToResolveAPIKey") </Condition>
</FaultRule>

관련 주제