API 키를 사용하여 인증

이 페이지에서는 API 키를 사용하여 API 키를 지원하는 Google Cloud APIs 및 서비스에 인증하는 방법을 설명합니다.

대부분의 Google Cloud APIs는 API 키를 지원하지 않습니다. 이 인증 방법을 사용하기 전에 사용하려는 API에서 API 키를 지원하는지 확인하세요.

API 키를 사용하여 Google Maps Platform을 인증하는 방법은 Google Maps Platform 문서를 참조하세요. API 키 API에 대한 자세한 내용은 API 키 API 문서를 참조하세요.

API 키 소개

API 키를 사용하여 API를 인증할 때 API 키는 주 구성원을 식별하거나 승인 정보를 제공하지 않습니다. 따라서 요청은 Identity and Access Management(IAM)를 사용하여 호출자에게 요청된 작업을 수행할 수 있는 권한이 있는지 확인하지 않습니다.

API 키는 청구 및 할당 목적으로 요청을 Google Cloud 프로젝트와 연결합니다. API 키가 호출자를 식별하지 않기 때문에 종종 공개 데이터 또는 리소스에 액세스하는 데 사용됩니다.

많은 Google Cloud API가 인증용으로 API 키를 수락하지 않습니다. API 키 지원 여부를 확인하기 위해 사용하려는 서비스 또는 API에 대해 인증 문서를 검토하세요.

API 키에는 키 관리 및 사용을 위해 사용되는 다음과 같은 구성요소가 포함되어 있습니다.

문자열
API 키 문자열은 AIzaSyDaGmWKa4JsXZ-HjGw7ISLn_3namBGewQe와 같은 암호화된 문자열입니다. API 키를 사용하여 인증할 때는 항상 키 문자열을 사용합니다. API 키에는 연결된 JSON 파일이 포함되지 않습니다.
ID
API 키 ID는 Google Cloud 관리 도구에서 키를 고유하게 식별하기 위해 사용됩니다. 키 ID는 인증에 사용될 수 없습니다. 키 ID는 Google Cloud 콘솔의 키 수정 페이지 URL에서 찾을 수 있습니다. Google Cloud CLI를 통해 프로젝트의 키를 나열하여 키 ID를 가져올 수도 있습니다.
표시 이름
표시 이름은 키를 만들거나 업데이트할 때 설정할 수 있는 키에 대한 선택적인 설명 이름입니다.

API 키를 관리하려면 프로젝트에 대해 API 키 관리자 역할(roles/serviceusage.apiKeysAdmin)이 있어야 합니다.

시작하기 전에

이 페이지의 샘플 사용 방법에 대한 탭을 선택하세요.

콘솔

Google Cloud 콘솔을 사용하여 Google Cloud 서비스 및 API에 액세스할 때는 인증을 설정할 필요가 없습니다.

gcloud

다음 개발 환경 중 하나에서 이 페이지의 gcloud CLI 샘플을 사용할 수 있습니다.

  • Cloud Shell: gcloud CLI가 이미 설정된 온라인 터미널을 사용하려면 Cloud Shell을 활성화하세요.

    이 페이지 하단에서 Cloud Shell 세션이 시작되고 명령줄 프롬프트가 표시됩니다. 세션이 초기화되는 데 몇 초 정도 걸릴 수 있습니다.

  • 로컬 셸: 로컬 개발 환경에서 gcloud CLI를 사용하려면 gcloud CLI를 설치하고 초기화합니다.

Java

로컬 개발 환경에서 이 페이지의 Java 샘플을 사용하려면 gcloud CLI를 설치 및 초기화한 다음 사용자 인증 정보로 애플리케이션 기본 사용자 인증 정보를 설정하세요.

  1. Google Cloud CLI를 설치합니다.
  2. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

    gcloud init
  3. Google 계정의 로컬 인증 사용자 인증 정보를 만듭니다.

    gcloud auth application-default login

자세한 내용은 Google Cloud 인증 문서의 로컬 개발 환경 인증 설정을 참조하세요.

Python

로컬 개발 환경에서 이 페이지의 Python 샘플을 사용하려면 gcloud CLI를 설치 및 초기화한 다음 사용자 인증 정보로 애플리케이션 기본 사용자 인증 정보를 설정하세요.

  1. Google Cloud CLI를 설치합니다.
  2. gcloud CLI를 초기화하려면 다음 명령어를 실행합니다.

    gcloud init
  3. Google 계정의 로컬 인증 사용자 인증 정보를 만듭니다.

    gcloud auth application-default login

자세한 내용은 Google Cloud 인증 문서의 로컬 개발 환경 인증 설정을 참조하세요.

REST

로컬 개발 환경에서 이 페이지의 REST API 샘플을 사용하려면 gcloud CLI에 제공한 사용자 인증 정보를 사용합니다.

    Google Cloud CLI를 설치한 후 다음 명령어를 실행하여 초기화합니다.

    gcloud init

API 키 만들기

API 키를 만들려면 다음 옵션 중 하나를 사용합니다.

Console

  1. Google Cloud console에서 사용자 인증 정보 페이지로 이동합니다.

    사용자 인증 정보로 이동

  2. 사용자 인증 정보 만들기를 클릭한 후 메뉴에서 API 키를 선택합니다.

    API 키 생성 완료 대화상자에 새로 생성된 키의 문자열이 표시됩니다.

gcloud

gcloud beta services api-keys create 명령어를 사용하여 API 키를 만듭니다.

DISPLAY_NAME을 키의 설명 이름으로 바꿉니다.

 gcloud beta services api-keys create --display-name=DISPLAY_NAME
 

Java

이 샘플을 실행하려면 google-cloud-apikeys 클라이언트 라이브러리를 설치해야 합니다.


import com.google.api.apikeys.v2.ApiKeysClient;
import com.google.api.apikeys.v2.ApiTarget;
import com.google.api.apikeys.v2.CreateKeyRequest;
import com.google.api.apikeys.v2.Key;
import com.google.api.apikeys.v2.LocationName;
import com.google.api.apikeys.v2.Restrictions;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class CreateApiKey {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(Developer): Before running this sample,
    //  1. Replace the variable(s) below.
    //  2. Set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
    //  3. Make sure you have the necessary permission to create API keys.
    String projectId = "GOOGLE_CLOUD_PROJECT_ID";

    createApiKey(projectId);
  }

  // Creates an API key.
  public static void createApiKey(String projectId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `apiKeysClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {

      Key key = Key.newBuilder()
          .setDisplayName("My first API key")
          // Set the API key restriction.
          // You can also set browser/ server/ android/ ios based restrictions.
          // For more information on API key restriction, see:
          // https://cloud.google.com/docs/authentication/api-keys#api_key_restrictions
          .setRestrictions(Restrictions.newBuilder()
              // Restrict the API key usage by specifying the target service and methods.
              // The API key can only be used to authenticate the specified methods in the service.
              .addApiTargets(ApiTarget.newBuilder()
                  .setService("translate.googleapis.com")
                  .addMethods("translate.googleapis.com.TranslateText")
                  .build())
              .build())
          .build();

      // Initialize request and set arguments.
      CreateKeyRequest createKeyRequest = CreateKeyRequest.newBuilder()
          // API keys can only be global.
          .setParent(LocationName.of(projectId, "global").toString())
          .setKey(key)
          .build();

      // Make the request and wait for the operation to complete.
      Key result = apiKeysClient.createKeyAsync(createKeyRequest).get(3, TimeUnit.MINUTES);

      // For authenticating with the API key, use the value in "result.getKeyString()".
      // To restrict the usage of this API key, use the value in "result.getName()".
      System.out.printf("Successfully created an API key: %s", result.getName());
    }
  }
}

Python

이 샘플을 실행하려면 API 키 클라이언트 라이브러리를 설치해야 합니다.


from google.cloud import api_keys_v2
from google.cloud.api_keys_v2 import Key

def create_api_key(project_id: str, suffix: str) -> Key:
    """
    Creates and restrict an API key. Add the suffix for uniqueness.

    TODO(Developer):
    1. Before running this sample,
      set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
    2. Make sure you have the necessary permission to create API keys.

    Args:
        project_id: Google Cloud project id.

    Returns:
        response: Returns the created API Key.
    """
    # Create the API Keys client.
    client = api_keys_v2.ApiKeysClient()

    key = api_keys_v2.Key()
    key.display_name = f"My first API key - {suffix}"

    # Initialize request and set arguments.
    request = api_keys_v2.CreateKeyRequest()
    request.parent = f"projects/{project_id}/locations/global"
    request.key = key

    # Make the request and wait for the operation to complete.
    response = client.create_key(request=request).result()

    print(f"Successfully created an API key: {response.name}")
    # For authenticating with the API key, use the value in "response.key_string".
    # To restrict the usage of this API key, use the value in "response.name".
    return response

REST

keys.create 메서드를 사용하여 API 키를 만듭니다. 이 요청은 장기 실행 작업을 반환합니다. 새 키에 대한 정보를 가져오려면 작업을 폴링해야 합니다.

다음 값을 바꿉니다.

  • DISPLAY_NAME: 선택사항. 키에 대한 설명 이름입니다.
  • PROJECT_ID: Google Cloud 프로젝트 ID 또는 이름입니다.
curl -X POST \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
-d {'"displayName" : "DISPLAY_NAME"'} \
"https://apikeys.googleapis.com/v2/projects/PROJECT/locations/global/keys"

REST API를 사용하여 API 키 만들기에 대한 자세한 내용은 API 키 API 문서에서 API 키 만들기를 참조하세요.

키 문자열을 복사하여 안전하게 보관해야 합니다. 테스트 키를 사용 중이고 나중에 이를 삭제하려는 경우가 아니면 애플리케이션 및 API 키 제한사항을 추가하세요.

API 키 사용

API가 API 키 사용을 지원하는 경우 API 키를 사용하여 해당 API를 인증할 수 있습니다. REST 요청 및 이를 지원하는 클라이언트 라이브러리에 API 키를 사용할 수 있습니다.

REST에 API 키 사용

다음 형식에 따라 API 키를 REST API 호출에 쿼리 매개변수로 전달할 수 있습니다. API_KEY를 API 키의 키 문자열로 바꿉니다.

예를 들어 documents.analyzeEntities Cloud Natural Language API 요청에 API 키를 전달하려면 다음 명령어를 입력합니다.

POST https://language.googleapis.com/v1/documents:analyzeEntities?key=API_KEY

또는 x-goog-api-key 헤더를 사용하여 키를 전달할 수 있습니다. 이 헤더는 gRPC 요청에 사용해야 합니다.

curl -X POST \
    -H "X-goog-api-key: API_KEY" \
    -H "Content-Type: application/json; charset=utf-8" \
    -d @request.json \
    "https://translation.googleapis.com/language/translate/v2"

클라이언트 라이브러리에 API 키 사용

API 키에 대한 클라이언트 라이브러리 지원은 언어별로 다릅니다.

Python

이 예시에서는 인증에 API 키를 지원하는 Cloud Natural Language API를 사용하여 API 키를 라이브러리에 제공하는 방법을 보여줍니다.

이 샘플을 실행하려면 Natural Language 클라이언트 라이브러리API 키 클라이언트 라이브러리를 설치해야 합니다.


from google.cloud import language_v1

def authenticate_with_api_key(quota_project_id: str, api_key_string: str) -> None:
    """
    Authenticates with an API key for Google Language service.

    TODO(Developer): Replace these variables before running the sample.

    Args:
        quota_project_id: Google Cloud project id that should be used for quota and billing purposes.
        api_key_string: The API key to authenticate to the service.
    """

    # Initialize the Language Service client and set the API key and the quota project id.
    client = language_v1.LanguageServiceClient(
        client_options={"api_key": api_key_string, "quota_project_id": quota_project_id}
    )

    text = "Hello, world!"
    document = language_v1.Document(
        content=text, type_=language_v1.Document.Type.PLAIN_TEXT
    )

    # Make a request to analyze the sentiment of the text.
    sentiment = client.analyze_sentiment(
        request={"document": document}
    ).document_sentiment

    print(f"Text: {text}")
    print(f"Sentiment: {sentiment.score}, {sentiment.magnitude}")
    print("Successfully authenticated using the API key")

API 키 보호

애플리케이션에서 API 키를 사용하는 경우 저장 및 전송 중에 안전하게 보호되도록 해야 합니다. API 키를 공개적으로 노출하면 계정에 예상치 않은 비용이 부과될 수 있습니다. API 키를 안전하게 보호하기 위해서는 다음 권장사항을 따르세요.

  • API 키 제한사항을 키에 추가합니다.

    제한사항을 추가하면 API 키 사용 방법을 제한하여 손상된 API 키로 인한 영향을 줄일 수 있습니다.

  • 공격에 노출되는 것을 최소화하기 위해 불필요한 API 키는 삭제합니다.

  • API 키를 주기적으로 다시 만듭니다.

    새 API 키를 주기적으로 만들고, 이전 키를 삭제하고, 새 API 키를 사용하도록 애플리케이션을 업데이트해야 합니다.

API 키 제한사항 적용

API 키는 기본적으로 무제한 상태입니다. 무제한 키는 어디서나 사용할 수 있으므로 안전하지 않습니다. 프로덕션 애플리케이션의 경우 애플리케이션 제한사항API 제한사항을 모두 설정해야 합니다.

애플리케이션 제한사항 추가

애플리케이션 제한사항은 API 키를 사용할 수 있는 웹사이트, IP 주소 또는 앱을 지정합니다.

애플리케이션 제한사항 유형은 한 번에 하나만 적용할 수 있습니다. 애플리케이션 유형을 기반으로 제한사항 유형을 선택합니다.

옵션 애플리케이션 유형 참고
HTTP 리퍼러 웹 애플리케이션 키를 사용할 수 있는 웹사이트를 지정합니다.
IP 주소 특정 서버에서 호출되는 애플리케이션 키를 사용할 수 있는 서버 또는 크론 작업을 지정합니다.
Android 앱 Android 애플리케이션 키를 사용할 수 있는 Android 애플리케이션을 지정합니다.
iOS 앱 iOS 애플리케이션 키를 사용할 수 있는 iOS 번들을 지정합니다.

HTTP 리퍼러

API 키를 사용할 수 있는 웹사이트를 제한하려면 하나 이상의 HTTP 리퍼러 제한사항을 추가합니다.

하위 도메인 또는 경로를 와일드 카드 문자(*)로 대체할 수 있지만 URL 중간에 와일드 카드 문자를 삽입할 수는 없습니다. 예를 들어 *.google.com은 유효하고 .google.com으로 끝나는 모든 사이트를 허용합니다. 그러나 mysubdomain*.google.com은 유효한 제한사항이 아닙니다.

HTTP 리퍼러 제한사항에 포트 번호를 포함할 수 있습니다. 포트 번호를 포함하면 해당 포트를 사용하는 요청만 일치합니다. 포트 번호를 지정하지 않으면 모든 포트 번호의 요청이 일치합니다.

API 키에는 최대 1,200개까지 HTTP 리퍼러를 추가할 수 있습니다.

다음 표에서는 일부 예시 시나리오 및 브라우저 제한사항을 보여줍니다.

시나리오 제한사항
특정 URL을 허용합니다. 정확한 경로를 가진 URL을 추가합니다. 예를 들면 다음과 같습니다.
www.example.com/path
www.example.com/path/path

일부 브라우저는 교차 출처 요청의 출처 URL만 전송하는 리퍼러 정책을 구현합니다. 이러한 브라우저의 사용자는 페이지별 URL 제한이 있는 키를 사용할 수 없습니다.

사이트의 모든 URL 허용 allowedReferers 목록에 2개의 URL을 설정해야 합니다.
  1. 하위 도메인이 없고 경로에 와일드 카드가 사용된 도메인의 URL입니다. 예를 들면 다음과 같습니다.
    example.com/*
  2. 하위 도메인에 대한 와일드 카드 및 경로에 대한 와일드 카드가 포함된 두 번째 URL입니다. 예를 들면 다음과 같습니다.
    *.example.com/*
단일 하위 도메인 또는 네이키드 도메인의 모든 URL을 허용합니다.

전체 도메인을 허용하도록 allowedReferers 목록에 2개의 URL을 설정해야 합니다.

  1. 후행 슬래시가 없는 도메인의 URL입니다. 예를 들면 다음과 같습니다.
    www.example.com
    sub.example.com
    example.com
  2. 경로에 대한 와일드 카드가 포함된 도메인의 두 번째 URL입니다. 예를 들면 다음과 같습니다.
    www.example.com/*
    sub.example.com/*
    example.com/*

특정 웹사이트로 API 키를 제한하려면 다음 옵션 중 하나를 사용합니다.

Console

  1. Google Cloud console에서 사용자 인증 정보 페이지로 이동합니다.

    사용자 인증 정보로 이동

  2. 제한하려는 API 키의 이름을 클릭합니다.

  3. 애플리케이션 제한사항 섹션에서 HTTP 리퍼러를 선택합니다.

  4. 추가할 각 제한사항에 대해 항목 추가를 클릭하고 제한사항을 입력하고, 완료를 클릭합니다.

  5. 저장을 클릭하여 변경사항을 저장하고 API 키 목록으로 돌아갑니다.

gcloud

  1. 제한하려는 키의 ID를 가져옵니다.

    ID는 표시 이름 또는 키 문자열과 같지 않습니다. gcloud services api-keys list 명령어를 사용하여 프로젝트의 키를 나열해서 ID를 가져올 수 있습니다.

  2. gcloud beta services api-keys update 명령어를 사용하여 API 키에 HTTP 리퍼러 제한사항을 추가합니다.

    다음 값을 바꿉니다.

    • KEY_ID: 제한하려는 키의 ID입니다.
    • ALLOWED_REFERRER_1: HTTP 리퍼러 제한사항입니다.

      필요한 수만큼 제한사항을 추가할 수 있습니다. 쉼표를 사용해서 제한사항을 구분합니다. 업데이트 명령어로 모든 리퍼러 제한사항을 제공해야 합니다. 제공된 리퍼러 제한사항은 키에서 기존 리퍼러 제한사항을 바꿉니다.

    gcloud beta services api-keys update KEY_ID \
     --allowed-referrers="ALLOWED_REFERRER_1"
    

Java

이 샘플을 실행하려면 google-cloud-apikeys 클라이언트 라이브러리를 설치해야 합니다.


import com.google.api.apikeys.v2.ApiKeysClient;
import com.google.api.apikeys.v2.BrowserKeyRestrictions;
import com.google.api.apikeys.v2.Key;
import com.google.api.apikeys.v2.Restrictions;
import com.google.api.apikeys.v2.UpdateKeyRequest;
import com.google.protobuf.FieldMask;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class RestrictApiKeyHttp {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(Developer): Before running this sample,
    //  1. Replace the variable(s) below.
    String projectId = "GOOGLE_CLOUD_PROJECT_ID";

    // ID of the key to restrict. This ID is auto-created during key creation.
    // This is different from the key string. To obtain the key_id,
    // you can also use the lookup api: client.lookupKey()
    String keyId = "key_id";

    restrictApiKeyHttp(projectId, keyId);
  }

  // Restricts an API key. To restrict the websites that can use your API key,
  // you add one or more HTTP referrer restrictions.
  public static void restrictApiKeyHttp(String projectId, String keyId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `apiKeysClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {

      // Restrict the API key usage to specific websites by adding them
      // to the list of allowed_referrers.
      Restrictions restrictions = Restrictions.newBuilder()
          .setBrowserKeyRestrictions(BrowserKeyRestrictions.newBuilder()
              .addAllowedReferrers("www.example.com/*")
              .build())
          .build();

      Key key = Key.newBuilder()
          .setName(String.format("projects/%s/locations/global/keys/%s", projectId, keyId))
          // Set the restriction(s).
          // For more information on API key restriction, see:
          // https://cloud.google.com/docs/authentication/api-keys
          .setRestrictions(restrictions)
          .build();

      // Initialize request and set arguments.
      UpdateKeyRequest updateKeyRequest = UpdateKeyRequest.newBuilder()
          .setKey(key)
          .setUpdateMask(FieldMask.newBuilder().addPaths("restrictions").build())
          .build();

      // Make the request and wait for the operation to complete.
      Key result = apiKeysClient.updateKeyAsync(updateKeyRequest).get(3, TimeUnit.MINUTES);

      // For authenticating with the API key, use the value in "result.getKeyString()".
      System.out.printf("Successfully updated the API key: %s", result.getName());
    }
  }
}

Python

이 샘플을 실행하려면 API 키 클라이언트 라이브러리를 설치해야 합니다.


from google.cloud import api_keys_v2
from google.cloud.api_keys_v2 import Key

def restrict_api_key_http(project_id: str, key_id: str) -> Key:
    """
    Restricts an API key. To restrict the websites that can use your API key,
    you add one or more HTTP referrer restrictions.

    TODO(Developer): Replace the variables before running this sample.

    Args:
        project_id: Google Cloud project id.
        key_id: ID of the key to restrict. This ID is auto-created during key creation.
            This is different from the key string. To obtain the key_id,
            you can also use the lookup api: client.lookup_key()

    Returns:
        response: Returns the updated API Key.
    """

    # Create the API Keys client.
    client = api_keys_v2.ApiKeysClient()

    # Restrict the API key usage to specific websites by adding them to the list of allowed_referrers.
    browser_key_restrictions = api_keys_v2.BrowserKeyRestrictions()
    browser_key_restrictions.allowed_referrers = ["www.example.com/*"]

    # Set the API restriction.
    # For more information on API key restriction, see:
    # https://cloud.google.com/docs/authentication/api-keys
    restrictions = api_keys_v2.Restrictions()
    restrictions.browser_key_restrictions = browser_key_restrictions

    key = api_keys_v2.Key()
    key.name = f"projects/{project_id}/locations/global/keys/{key_id}"
    key.restrictions = restrictions

    # Initialize request and set arguments.
    request = api_keys_v2.UpdateKeyRequest()
    request.key = key
    request.update_mask = "restrictions"

    # Make the request and wait for the operation to complete.
    response = client.update_key(request=request).result()

    print(f"Successfully updated the API key: {response.name}")
    # Use response.key_string to authenticate.
    return response

REST

  1. 제한하려는 키의 ID를 가져옵니다.

    ID는 표시 이름 또는 키 문자열과 같지 않습니다. keys.list 메서드를 사용하여 ID를 가져올 수 있습니다. ID는 응답의 uid 필드에 나열됩니다.

    PROJECT_ID를 Google Cloud 프로젝트 ID 또는 이름으로 바꿉니다.

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/"
    
  2. keys.patch 메서드를 사용하여 HTTP 리퍼러 제한을 API 키에 추가합니다.

    이 요청은 장기 실행 작업을 반환합니다. 작업이 완료되는 시간을 확인하고 작업 상태를 가져오려면 작업을 폴링해야 합니다.

    다음 값을 바꿉니다.

    • ALLOWED_REFERRER_1: HTTP 리퍼러 제한사항입니다.

      필요한 수만큼 제한사항을 추가할 수 있습니다. 쉼표를 사용해서 제한사항을 구분합니다. 요청에 모든 리퍼러 제한사항을 제공해야 합니다. 제공된 리퍼러 제한사항은 키에서 기존 리퍼러 제한사항을 바꿉니다.

    • PROJECT_ID: Google Cloud 프로젝트 ID 또는 이름입니다.

    • KEY_ID: 제한하려는 키의 ID입니다.

    curl -X PATCH \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    --data '{
    "restrictions" : {
    "browserKeyRestrictions": {
      "allowedReferrers": ["ALLOWED_REFERRER_1"]
    }
    }
    }' \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"
    

REST API를 사용하여 키에 HTTP 리퍼러 제한사항을 추가하는 방법은 API 키 API 문서에서 브라우저 제한사항 추가를 참조하세요.

IP 주소

API 키를 사용할 수 있는 웹 서버 또는 크론 작업과 같은 호출자의 IP 주소를 하나 이상 지정할 수 있습니다. 다음 형식으로 IP 주소를 지정할 수 있습니다.

  • IPv4(198.51.100.1)
  • IPv6(2001:db8::1)
  • CIDR 표기법을 사용하는 서브넷(198.51.100.0/24, 2001:db8::/64)

서버 제한사항에는 localhost 사용이 지원되지 않습니다.

특정 IP 주소로 API 키를 제한하려면 다음 옵션 중 하나를 사용합니다.

Console

  1. Google Cloud console에서 사용자 인증 정보 페이지로 이동합니다.

    사용자 인증 정보로 이동

  2. 제한하려는 API 키의 이름을 클릭합니다.

  3. 애플리케이션 제한사항 섹션에서 IP 주소를 선택합니다.

  4. 추가하려는 각 IP 주소에 대해 항목 추가를 클릭하고 주소를 입력하고 완료를 클릭합니다.

  5. 저장을 클릭하여 변경사항을 저장하고 API 키 목록으로 돌아갑니다.

gcloud

  1. 제한하려는 키의 ID를 가져옵니다.

    ID는 표시 이름 또는 키 문자열과 같지 않습니다. gcloud services api-keys list 명령어를 사용하여 프로젝트의 키를 나열해서 ID를 가져올 수 있습니다.

  2. gcloud beta services api-keys update 명령어를 사용하여 API 키에 서버(IP 주소) 제한사항을 추가합니다.

    다음 값을 바꿉니다.

    • KEY_ID: 제한하려는 키의 ID입니다.
    • ALLOWED_IP_ADDR_1: 허용되는 IP 주소입니다.

      필요한 수만큼 IP 주소를 추가할 수 있습니다. 쉼표를 사용하여 주소를 구분합니다.

    gcloud beta services api-keys update KEY_ID \
    --allowed-ips="ALLOWED_IP_ADDR_1"
    

Java

이 샘플을 실행하려면 google-cloud-apikeys 클라이언트 라이브러리를 설치해야 합니다.


import com.google.api.apikeys.v2.ApiKeysClient;
import com.google.api.apikeys.v2.Key;
import com.google.api.apikeys.v2.Restrictions;
import com.google.api.apikeys.v2.ServerKeyRestrictions;
import com.google.api.apikeys.v2.UpdateKeyRequest;
import com.google.protobuf.FieldMask;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class RestrictApiKeyServer {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(Developer): Before running this sample,
    //  1. Replace the variable(s) below.
    String projectId = "GOOGLE_CLOUD_PROJECT_ID";

    // ID of the key to restrict. This ID is auto-created during key creation.
    // This is different from the key string. To obtain the key_id,
    // you can also use the lookup api: client.lookupKey()
    String keyId = "key_id";

    restrictApiKeyServer(projectId, keyId);
  }

  // Restricts the API key based on IP addresses. You can specify one or more IP addresses
  // of the callers, for example web servers or cron jobs, that are allowed to use your API key.
  public static void restrictApiKeyServer(String projectId, String keyId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `apiKeysClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {

      // Restrict the API key usage by specifying the IP addresses.
      // You can specify the IP addresses in IPv4 or IPv6 or a subnet using CIDR notation.
      Restrictions restrictions = Restrictions.newBuilder()
          .setServerKeyRestrictions(ServerKeyRestrictions.newBuilder()
              .addAllAllowedIps(Arrays.asList("198.51.100.0/24", "2000:db8::/64"))
              .build())
          .build();

      Key key = Key.newBuilder()
          .setName(String.format("projects/%s/locations/global/keys/%s", projectId, keyId))
          // Set the restriction(s).
          // For more information on API key restriction, see:
          // https://cloud.google.com/docs/authentication/api-keys
          .setRestrictions(restrictions)
          .build();

      // Initialize request and set arguments.
      UpdateKeyRequest updateKeyRequest = UpdateKeyRequest.newBuilder()
          .setKey(key)
          .setUpdateMask(FieldMask.newBuilder().addPaths("restrictions").build())
          .build();

      // Make the request and wait for the operation to complete.
      Key result = apiKeysClient.updateKeyAsync(updateKeyRequest).get(3, TimeUnit.MINUTES);

      // For authenticating with the API key, use the value in "result.getKeyString()".
      System.out.printf("Successfully updated the API key: %s", result.getName());
    }
  }
}

Python

이 샘플을 실행하려면 API 키 클라이언트 라이브러리를 설치해야 합니다.


from google.cloud import api_keys_v2
from google.cloud.api_keys_v2 import Key

def restrict_api_key_server(project_id: str, key_id: str) -> Key:
    """
    Restricts the API key based on IP addresses. You can specify one or more IP addresses of the callers,
    for example web servers or cron jobs, that are allowed to use your API key.

    TODO(Developer): Replace the variables before running this sample.

    Args:
        project_id: Google Cloud project id.
        key_id: ID of the key to restrict. This ID is auto-created during key creation.
            This is different from the key string. To obtain the key_id,
            you can also use the lookup api: client.lookup_key()

    Returns:
        response: Returns the updated API Key.
    """

    # Create the API Keys client.
    client = api_keys_v2.ApiKeysClient()

    # Restrict the API key usage by specifying the IP addresses.
    # You can specify the IP addresses in IPv4 or IPv6 or a subnet using CIDR notation.
    server_key_restrictions = api_keys_v2.ServerKeyRestrictions()
    server_key_restrictions.allowed_ips = ["198.51.100.0/24", "2000:db8::/64"]

    # Set the API restriction.
    # For more information on API key restriction, see:
    # https://cloud.google.com/docs/authentication/api-keys
    restrictions = api_keys_v2.Restrictions()
    restrictions.server_key_restrictions = server_key_restrictions

    key = api_keys_v2.Key()
    key.name = f"projects/{project_id}/locations/global/keys/{key_id}"
    key.restrictions = restrictions

    # Initialize request and set arguments.
    request = api_keys_v2.UpdateKeyRequest()
    request.key = key
    request.update_mask = "restrictions"

    # Make the request and wait for the operation to complete.
    response = client.update_key(request=request).result()

    print(f"Successfully updated the API key: {response.name}")
    # Use response.key_string to authenticate.
    return response

REST

  1. 제한하려는 키의 ID를 가져옵니다.

    ID는 표시 이름 또는 키 문자열과 같지 않습니다. keys.list 메서드를 사용하여 ID를 가져올 수 있습니다. ID는 응답의 uid 필드에 나열됩니다.

    PROJECT_ID를 Google Cloud 프로젝트 ID 또는 이름으로 바꿉니다.

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/"
    
  2. keys.patch 메서드를 사용하여 API 키에 서버(IP 주소) 제한사항을 추가합니다.

    이 요청은 장기 실행 작업을 반환합니다. 작업이 완료되는 시간을 확인하고 작업 상태를 가져오려면 작업을 폴링해야 합니다.

    다음 값을 바꿉니다.

    • ALLOWED_IP_ADDR_1: 허용되는 IP 주소입니다.

      필요한 수만큼 IP 주소를 추가할 수 있습니다. 쉼표를 사용하여 제한사항을 구분합니다. 요청에 모든 IP 주소를 제공해야 합니다. 제공된 리퍼러 제한사항은 키에서 기존 IP 주소 제한사항을 바꿉니다.

    • PROJECT_ID: Google Cloud 프로젝트 ID 또는 이름입니다.

    • KEY_ID: 제한하려는 키의 ID입니다.

    curl -X PATCH \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    --data '{
    "restrictions" : {
      "serverKeyRestrictions": {
        "allowedIps": ["ALLOWED_IP_ADDR_1"]
      }
    }
    }' \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"
    

REST API를 사용하여 키에 IP 주소를 추가하는 방법은 API 키 API 문서에서 서버 제한사항 추가를 참조하세요.

Android 앱

API 키 사용을 특정 Android 앱으로 제한할 수 있습니다. 각 앱에 대해 패키지 이름과 20바이트 SHA-1 인증서 지문을 제공해야 합니다.

요청에 API 키를 사용하는 경우 다음 HTTP 헤더를 사용하여 패키지 이름과 인증서 지문을 지정해야 합니다.

  • X-Android-Package
  • X-Android-Cert

API 키를 하나 이상의 Android 앱으로 제한하려면 다음 옵션 중 하나를 사용합니다.

Console

  1. Google Cloud console에서 사용자 인증 정보 페이지로 이동합니다.

    사용자 인증 정보로 이동

  2. 제한하려는 API 키의 이름을 클릭합니다.

  3. 애플리케이션 제한사항 섹션에서 Android 앱을 선택합니다.

  4. 추가하려는 각 Android 앱에 대해 항목 추가를 클릭하고 패키지 이름과 SHA-1 인증서 지문을 입력한 후 완료를 클릭합니다.

  5. 저장을 클릭하여 변경사항을 저장하고 API 키 목록으로 돌아갑니다.

gcloud

  1. 제한하려는 키의 ID를 가져옵니다.

    ID는 표시 이름 또는 키 문자열과 같지 않습니다. gcloud services api-keys list 명령어를 사용하여 프로젝트의 키를 나열해서 ID를 가져올 수 있습니다.

  2. gcloud beta services api-keys update 명령어를 사용하여 API 키를 사용할 수 있는 Android 앱을 지정합니다.

    다음 값을 바꿉니다.

    • KEY_ID: 제한하려는 키의 ID입니다.
    • SHA1_FINGERPRINTPACKAGE_NAME: 키를 사용할 수 있는 Android 앱에 대한 앱 정보입니다.

      필요한 수만큼 앱을 추가할 수 있습니다. 추가 --allowed-application 플래그를 사용하세요.

    gcloud beta services api-keys update KEY_ID \
    --allowed-application=sha1_fingerprint=SHA1_FINGERPRINT_1,package_name=PACKAGE_NAME_1 \
    --allowed-application=sha1_fingerprint=SHA1_FINGERPRINT_2,package_name=PACKAGE_NAME_2
    

Java

이 샘플을 실행하려면 google-cloud-apikeys 클라이언트 라이브러리를 설치해야 합니다.


import com.google.api.apikeys.v2.AndroidApplication;
import com.google.api.apikeys.v2.AndroidKeyRestrictions;
import com.google.api.apikeys.v2.ApiKeysClient;
import com.google.api.apikeys.v2.Key;
import com.google.api.apikeys.v2.Restrictions;
import com.google.api.apikeys.v2.UpdateKeyRequest;
import com.google.protobuf.FieldMask;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class RestrictApiKeyAndroid {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(Developer): Before running this sample,
    //  1. Replace the variable(s) below.
    String projectId = "GOOGLE_CLOUD_PROJECT_ID";

    // ID of the key to restrict. This ID is auto-created during key creation.
    // This is different from the key string. To obtain the key_id,
    // you can also use the lookup api: client.lookupKey()
    String keyId = "key_id";

    restrictApiKeyAndroid(projectId, keyId);
  }

  // Restricts an API key based on android applications.
  // Specifies the Android application that can use the key.
  public static void restrictApiKeyAndroid(String projectId, String keyId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `apiKeysClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {

      // Restrict the API key usage by specifying the allowed android applications.
      Restrictions restrictions = Restrictions.newBuilder()
          .setAndroidKeyRestrictions(AndroidKeyRestrictions.newBuilder()
              .addAllowedApplications(AndroidApplication.newBuilder()
                  // Specify the android application's package name and SHA1 fingerprint.
                  .setPackageName("com.google.appname")
                  .setSha1Fingerprint("0873D391E987982FBBD30873D391E987982FBBD3")
                  .build())
              .build())
          .build();

      Key key = Key.newBuilder()
          .setName(String.format("projects/%s/locations/global/keys/%s", projectId, keyId))
          // Set the restriction(s).
          // For more information on API key restriction, see:
          // https://cloud.google.com/docs/authentication/api-keys
          .setRestrictions(restrictions)
          .build();

      // Initialize request and set arguments.
      UpdateKeyRequest updateKeyRequest = UpdateKeyRequest.newBuilder()
          .setKey(key)
          .setUpdateMask(FieldMask.newBuilder().addPaths("restrictions").build())
          .build();

      // Make the request and wait for the operation to complete.
      Key result = apiKeysClient.updateKeyAsync(updateKeyRequest).get(3, TimeUnit.MINUTES);

      // For authenticating with the API key, use the value in "result.getKeyString()".
      System.out.printf("Successfully updated the API key: %s", result.getName());
    }
  }
}

Python

이 샘플을 실행하려면 API 키 클라이언트 라이브러리를 설치해야 합니다.


from google.cloud import api_keys_v2
from google.cloud.api_keys_v2 import Key

def restrict_api_key_android(project_id: str, key_id: str) -> Key:
    """
    Restricts an API key based on android applications.

    Specifies the Android application that can use the key.

    TODO(Developer): Replace the variables before running this sample.

    Args:
        project_id: Google Cloud project id.
        key_id: ID of the key to restrict. This ID is auto-created during key creation.
            This is different from the key string. To obtain the key_id,
            you can also use the lookup api: client.lookup_key()

    Returns:
        response: Returns the updated API Key.
    """

    # Create the API Keys client.
    client = api_keys_v2.ApiKeysClient()

    # Specify the android application's package name and SHA1 fingerprint.
    allowed_application = api_keys_v2.AndroidApplication()
    allowed_application.package_name = "com.google.appname"
    allowed_application.sha1_fingerprint = "0873D391E987982FBBD30873D391E987982FBBD3"

    # Restrict the API key usage by specifying the allowed applications.
    android_key_restriction = api_keys_v2.AndroidKeyRestrictions()
    android_key_restriction.allowed_applications = [allowed_application]

    # Set the restriction(s).
    # For more information on API key restriction, see:
    # https://cloud.google.com/docs/authentication/api-keys
    restrictions = api_keys_v2.Restrictions()
    restrictions.android_key_restrictions = android_key_restriction

    key = api_keys_v2.Key()
    key.name = f"projects/{project_id}/locations/global/keys/{key_id}"
    key.restrictions = restrictions

    # Initialize request and set arguments.
    request = api_keys_v2.UpdateKeyRequest()
    request.key = key
    request.update_mask = "restrictions"

    # Make the request and wait for the operation to complete.
    response = client.update_key(request=request).result()

    print(f"Successfully updated the API key: {response.name}")
    # Use response.key_string to authenticate.
    return response

REST

  1. 제한하려는 키의 ID를 가져옵니다.

    ID는 표시 이름 또는 키 문자열과 같지 않습니다. keys.list 메서드를 사용하여 ID를 가져올 수 있습니다. ID는 응답의 uid 필드에 나열됩니다.

    PROJECT_ID를 Google Cloud 프로젝트 ID 또는 이름으로 바꿉니다.

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/"
    
  2. keys.patch 메서드를 사용하여 API 키를 사용할 수 있는 Android 앱을 지정합니다.

    이 요청은 장기 실행 작업을 반환합니다. 작업이 완료되는 시간을 확인하고 작업 상태를 가져오려면 작업을 폴링해야 합니다.

    다음 값을 바꿉니다.

    • SHA1_FINGERPRINT_1PACKAGE_NAME_1: 키를 사용할 수 있는 Android 앱에 대한 앱 정보입니다.

      필요한 수만큼 앱에 대한 정보를 추가할 수 있습니다. 쉼표를 사용하여 AndroidApplication 객체를 구분합니다. 요청에 모든 애플리케이션을 제공해야 합니다. 제공된 애플리케이션은 키에서 기존 허용되는 애플리케이션을 바꿉니다.

    • PROJECT_ID: Google Cloud 프로젝트 ID 또는 이름입니다.

    • KEY_ID: 제한하려는 키의 ID입니다.

    curl -X PATCH \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    --data '{
    "restrictions" : {
    "androidKeyRestrictions": {
      "allowedApplications": [
        {
          "sha1Fingerprint": "SHA1_FINGERPRINT_1",
          "packageName": "PACKAGE_NAME_1"
        },
     ]
    }
    }
    }' \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"
    

REST API를 사용하여 키에 Android 앱 제한사항을 추가하는 방법은 API 키 API 문서에서 Android 제한사항 추가를 참조하세요.

iOS 앱

각 앱의 번들 ID를 제공하여 API 키 사용을 특정 iOS 앱으로 제한할 수 있습니다.

요청에 API 키를 사용하는 경우 X-Ios-Bundle-Identifier HTTP 헤더를 사용하여 번들 ID를 지정해야 합니다.

API 키를 하나 이상의 iOS 앱으로 제한하려면 다음 옵션 중 하나를 사용합니다.

Console

  1. Google Cloud console에서 사용자 인증 정보 페이지로 이동합니다.

    사용자 인증 정보로 이동

  2. 제한하려는 API 키의 이름을 클릭합니다.

  3. 애플리케이션 제한사항 섹션에서 iOS 앱을 선택합니다.

  4. 추가하려는 각 iOS 앱에 대해 항목 추가를 클릭하고 번들 ID를 입력한 후 완료를 클릭합니다.

  5. 저장을 클릭하여 변경사항을 저장하고 API 키 목록으로 돌아갑니다.

gcloud

  1. 제한하려는 키의 ID를 가져옵니다.

    ID는 표시 이름 또는 키 문자열과 같지 않습니다. gcloud services api-keys list 명령어를 사용하여 프로젝트의 키를 나열해서 ID를 가져올 수 있습니다.

  2. gcloud beta services api-keys update 메서드를 사용하여 키를 사용할 수 있는 iOS 앱을 지정합니다.

    다음 값을 바꿉니다.

    • KEY_ID: 제한하려는 키의 ID입니다.
    • ALLOWED_BUNDLE_ID: 이 API 키를 사용할 수 있게 하려는 iOS 앱의 번들 ID입니다.

      필요한 수만큼 번들 ID를 추가할 수 있습니다. 쉼표를 사용하여 ID를 구분합니다.

    gcloud beta services api-keys update KEY_ID \
    --allowed-bundle-ids=ALLOWED_BUNDLE_ID_1,ALLOWED_BUNDLE_ID_2
    

Java

이 샘플을 실행하려면 google-cloud-apikeys 클라이언트 라이브러리를 설치해야 합니다.


import com.google.api.apikeys.v2.ApiKeysClient;
import com.google.api.apikeys.v2.IosKeyRestrictions;
import com.google.api.apikeys.v2.Key;
import com.google.api.apikeys.v2.Restrictions;
import com.google.api.apikeys.v2.UpdateKeyRequest;
import com.google.protobuf.FieldMask;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class RestrictApiKeyIos {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(Developer): Before running this sample,
    //  1. Replace the variable(s) below.
    String projectId = "GOOGLE_CLOUD_PROJECT_ID";

    // ID of the key to restrict. This ID is auto-created during key creation.
    // This is different from the key string. To obtain the key_id,
    // you can also use the lookup api: client.lookupKey()
    String keyId = "key_id";

    restrictApiKeyIos(projectId, keyId);
  }

  // Restricts an API key. You can restrict usage of an API key to specific iOS apps
  // by providing the bundle ID of each app.
  public static void restrictApiKeyIos(String projectId, String keyId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `apiKeysClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {

      // Restrict the API key usage by specifying the bundle ID(s)
      // of iOS app(s) that can use the key.
      Restrictions restrictions = Restrictions.newBuilder()
          .setIosKeyRestrictions(IosKeyRestrictions.newBuilder()
              .addAllAllowedBundleIds(Arrays.asList("com.google.gmail", "com.google.drive"))
              .build())
          .build();

      Key key = Key.newBuilder()
          .setName(String.format("projects/%s/locations/global/keys/%s", projectId, keyId))
          // Set the restriction(s).
          // For more information on API key restriction, see:
          // https://cloud.google.com/docs/authentication/api-keys
          .setRestrictions(restrictions)
          .build();

      // Initialize request and set arguments.
      UpdateKeyRequest updateKeyRequest = UpdateKeyRequest.newBuilder()
          .setKey(key)
          .setUpdateMask(FieldMask.newBuilder().addPaths("restrictions").build())
          .build();

      // Make the request and wait for the operation to complete.
      Key result = apiKeysClient.updateKeyAsync(updateKeyRequest).get(3, TimeUnit.MINUTES);

      // For authenticating with the API key, use the value in "result.getKeyString()".
      System.out.printf("Successfully updated the API key: %s", result.getName());
    }
  }
}

Python

이 샘플을 실행하려면 API 키 클라이언트 라이브러리를 설치해야 합니다.


from google.cloud import api_keys_v2
from google.cloud.api_keys_v2 import Key

def restrict_api_key_ios(project_id: str, key_id: str) -> Key:
    """
    Restricts an API key. You can restrict usage of an API key to specific iOS apps
    by providing the bundle ID of each app.

    TODO(Developer): Replace the variables before running this sample.

    Args:
        project_id: Google Cloud project id.
        key_id: ID of the key to restrict. This ID is auto-created during key creation.
            This is different from the key string. To obtain the key_id,
            you can also use the lookup api: client.lookup_key()

    Returns:
        response: Returns the updated API Key.
    """

    # Create the API Keys client.
    client = api_keys_v2.ApiKeysClient()

    # Restrict the API key usage by specifying the bundle ID(s) of iOS app(s) that can use the key.
    ios_key_restrictions = api_keys_v2.IosKeyRestrictions()
    ios_key_restrictions.allowed_bundle_ids = ["com.google.gmail", "com.google.drive"]

    # Set the API restriction.
    # For more information on API key restriction, see:
    # https://cloud.google.com/docs/authentication/api-keys
    restrictions = api_keys_v2.Restrictions()
    restrictions.ios_key_restrictions = ios_key_restrictions

    key = api_keys_v2.Key()
    key.name = f"projects/{project_id}/locations/global/keys/{key_id}"
    key.restrictions = restrictions

    # Initialize request and set arguments.
    request = api_keys_v2.UpdateKeyRequest()
    request.key = key
    request.update_mask = "restrictions"

    # Make the request and wait for the operation to complete.
    response = client.update_key(request=request).result()

    print(f"Successfully updated the API key: {response.name}")
    # Use response.key_string to authenticate.
    return response

REST

  1. 제한하려는 키의 ID를 가져옵니다.

    ID는 표시 이름 또는 키 문자열과 같지 않습니다. keys.list 메서드를 사용하여 ID를 가져올 수 있습니다. ID는 응답의 uid 필드에 나열됩니다.

    PROJECT_ID를 Google Cloud 프로젝트 ID 또는 이름으로 바꿉니다.

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/"
    
  2. keys.patch 메서드를 사용하여 API 키를 사용할 수 있는 iOS 앱을 지정합니다.

    이 요청은 장기 실행 작업을 반환합니다. 작업이 완료되는 시간을 확인하고 작업 상태를 가져오려면 작업을 폴링해야 합니다.

    다음 값을 바꿉니다.

    • ALLOWED_BUNDLE_ID: 키를 사용할 수 있는 iOS 앱의 번들 ID입니다.

      필요한 수만큼 앱에 대한 정보를 추가할 수 있습니다. 쉼표를 사용하여 번들 ID를 구분합니다. 요청에 모든 번들 ID를 제공해야 합니다. 제공된 번들 ID는 키에서 기존 허용되는 애플리케이션을 바꿉니다.

    • PROJECT_ID: Google Cloud 프로젝트 ID 또는 이름입니다.

    • KEY_ID: 제한하려는 키의 ID입니다.

    curl -X PATCH \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    --data '{
    "restrictions" : {
    "iosKeyRestrictions": {
      "allowedBundleIds": ["ALLOWED_BUNDLE_ID_1","ALLOWED_BUNDLE_ID_2"]
    }
    }
    }' \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"
    

REST API를 사용하여 키에 iOS 앱 제한사항을 추가하는 방법은 API 키 API 문서에서 iOS 제한사항 추가를 참조하세요.

API 제한사항 추가

API 제한사항은 API 키를 사용해서 호출할 수 있는 API를 지정합니다.

API 제한사항을 추가하려면 다음 옵션 중 하나를 사용합니다.

Console

  1. Google Cloud console에서 사용자 인증 정보 페이지로 이동합니다.

    사용자 인증 정보로 이동

  2. 제한하려는 API 키의 이름을 클릭합니다.

  3. API 제한사항 섹션에서 키 제한을 클릭합니다.

  4. API 키가 액세스하는 데 사용될 모든 API를 선택합니다.

  5. 저장을 클릭하여 변경사항을 저장하고 API 키 목록으로 돌아갑니다.

gcloud

  1. 제한하려는 키의 ID를 가져옵니다.

    ID는 표시 이름 또는 키 문자열과 같지 않습니다. gcloud services api-keys list 명령어를 사용하여 프로젝트의 키를 나열해서 ID를 가져올 수 있습니다.

  2. gcloud beta services api-keys update 명령어를 사용하여 API 키를 인증에 사용할 수 있는 서비스를 지정합니다.

    다음 값을 바꿉니다.

    • KEY_ID: 제한하려는 키의 ID입니다.
    • SERVICE_1, SERVICE_2...: 키를 액세스에 사용할 수 있는 API의 서비스 이름입니다.

      업데이트 명령어에 모든 서비스 이름을 제공해야 합니다. 제공된 서비스 이름은 키에서 기존 서비스를 대체합니다.

    API 대시보드에서 API를 검색하여 서비스 이름을 찾을 수 있습니다. 서비스 이름은 bigquery.googleapis.com과 같은 문자열입니다.

    gcloud beta services api-keys update KEY_ID \
    --api-target=service=SERVICE_1 --api-target=service=SERVICE_2
    

Java

이 샘플을 실행하려면 google-cloud-apikeys 클라이언트 라이브러리를 설치해야 합니다.


import com.google.api.apikeys.v2.ApiKeysClient;
import com.google.api.apikeys.v2.ApiTarget;
import com.google.api.apikeys.v2.Key;
import com.google.api.apikeys.v2.Restrictions;
import com.google.api.apikeys.v2.UpdateKeyRequest;
import com.google.protobuf.FieldMask;
import java.io.IOException;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

public class RestrictApiKeyApi {

  public static void main(String[] args)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // TODO(Developer): Before running this sample,
    //  1. Replace the variable(s) below.
    String projectId = "GOOGLE_CLOUD_PROJECT_ID";

    // ID of the key to restrict. This ID is auto-created during key creation.
    // This is different from the key string. To obtain the key_id,
    // you can also use the lookup api: client.lookupKey()
    String keyId = "key_id";

    restrictApiKeyApi(projectId, keyId);
  }

  // Restricts an API key. Restrictions specify which APIs can be called using the API key.
  public static void restrictApiKeyApi(String projectId, String keyId)
      throws IOException, ExecutionException, InterruptedException, TimeoutException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `apiKeysClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {

      // Restrict the API key usage by specifying the target service and methods.
      // The API key can only be used to authenticate the specified methods in the service.
      Restrictions restrictions = Restrictions.newBuilder()
          .addApiTargets(ApiTarget.newBuilder()
              .setService("translate.googleapis.com")
              .addMethods("translate.googleapis.com.TranslateText")
              .build())
          .build();

      Key key = Key.newBuilder()
          .setName(String.format("projects/%s/locations/global/keys/%s", projectId, keyId))
          // Set the restriction(s).
          // For more information on API key restriction, see:
          // https://cloud.google.com/docs/authentication/api-keys
          .setRestrictions(restrictions)
          .build();

      // Initialize request and set arguments.
      UpdateKeyRequest updateKeyRequest = UpdateKeyRequest.newBuilder()
          .setKey(key)
          .setUpdateMask(FieldMask.newBuilder().addPaths("restrictions").build())
          .build();

      // Make the request and wait for the operation to complete.
      Key result = apiKeysClient.updateKeyAsync(updateKeyRequest).get(3, TimeUnit.MINUTES);

      // For authenticating with the API key, use the value in "result.getKeyString()".
      System.out.printf("Successfully updated the API key: %s", result.getName());
    }
  }
}

Python

이 샘플을 실행하려면 API 키 클라이언트 라이브러리를 설치해야 합니다.


from google.cloud import api_keys_v2
from google.cloud.api_keys_v2 import Key

def restrict_api_key_api(project_id: str, key_id: str) -> Key:
    """
    Restricts an API key. Restrictions specify which APIs can be called using the API key.

    TODO(Developer): Replace the variables before running the sample.

    Args:
        project_id: Google Cloud project id.
        key_id: ID of the key to restrict. This ID is auto-created during key creation.
            This is different from the key string. To obtain the key_id,
            you can also use the lookup api: client.lookup_key()

    Returns:
        response: Returns the updated API Key.
    """

    # Create the API Keys client.
    client = api_keys_v2.ApiKeysClient()

    # Restrict the API key usage by specifying the target service and methods.
    # The API key can only be used to authenticate the specified methods in the service.
    api_target = api_keys_v2.ApiTarget()
    api_target.service = "translate.googleapis.com"
    api_target.methods = ["transate.googleapis.com.TranslateText"]

    # Set the API restriction(s).
    # For more information on API key restriction, see:
    # https://cloud.google.com/docs/authentication/api-keys
    restrictions = api_keys_v2.Restrictions()
    restrictions.api_targets = [api_target]

    key = api_keys_v2.Key()
    key.name = f"projects/{project_id}/locations/global/keys/{key_id}"
    key.restrictions = restrictions

    # Initialize request and set arguments.
    request = api_keys_v2.UpdateKeyRequest()
    request.key = key
    request.update_mask = "restrictions"

    # Make the request and wait for the operation to complete.
    response = client.update_key(request=request).result()

    print(f"Successfully updated the API key: {response.name}")
    # Use response.key_string to authenticate.
    return response

REST

  1. 제한하려는 키의 ID를 가져옵니다.

    ID는 표시 이름 또는 키 문자열과 같지 않습니다. keys.list 메서드를 사용하여 ID를 가져올 수 있습니다. ID는 응답의 uid 필드에 나열됩니다.

    PROJECT_ID를 Google Cloud 프로젝트 ID 또는 이름으로 바꿉니다.

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/"
    
  2. keys.patch 메서드를 사용하여 API 키를 인증에 사용할 수 있는 서비스를 지정합니다.

    이 요청은 장기 실행 작업을 반환합니다. 작업이 완료되는 시간을 확인하고 작업 상태를 가져오려면 작업을 폴링해야 합니다.

    다음 값을 바꿉니다.

    • SERVICE_1, SERVICE_2...: 키를 액세스에 사용할 수 있는 API의 서비스 이름입니다.

      요청에 모든 서비스 이름을 제공해야 합니다. 제공된 서비스 이름은 키에서 기존 서비스를 바꿉니다.

      API 대시보드에서 API를 검색하여 서비스 이름을 찾을 수 있습니다. 서비스 이름은 bigquery.googleapis.com과 같은 문자열입니다.

    • PROJECT_ID: Google Cloud 프로젝트 ID 또는 이름입니다.

    • KEY_ID: 제한하려는 키의 ID입니다.

    curl -X PATCH \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    --data '{
    "restrictions" : {
    "apiTargets": [
      {
        "service": "SERVICE_1"
      },
      {
        "service" : "SERVICE_2"
      },
    ]
    }
    }' \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID?updateMask=restrictions"
    

REST API를 사용하여 키에 API 제한사항을 추가하는 방법은 API 키 API 문서에서 API 제한사항 추가를 참조하세요.

키 문자열에서 프로젝트 정보 가져오기

문자열에서 API 키가 연결된 Google Cloud 프로젝트를 확인할 수 있습니다.

KEY_STRING을 프로젝트 정보가 필요한 키 문자열로 바꿉니다.

gcloud

gcloud beta services api-keys lookup 명령어를 사용하여 키 문자열에서 프로젝트 ID를 가져옵니다.

 gcloud beta services api-keys lookup KEY_STRING
 

Java

이 샘플을 실행하려면 google-cloud-apikeys 클라이언트 라이브러리를 설치해야 합니다.


import com.google.api.apikeys.v2.ApiKeysClient;
import com.google.api.apikeys.v2.LookupKeyRequest;
import com.google.api.apikeys.v2.LookupKeyResponse;
import java.io.IOException;

public class LookupApiKey {

  public static void main(String[] args) throws IOException {
    // TODO(Developer): Before running this sample,
    //  1. Replace the variable(s) below.
    //  2. Set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
    //  3. Make sure you have the necessary permission to view API keys.
    // API key string to retrieve the API key name.
    String apiKeyString = "API_KEY_STRING";

    lookupApiKey(apiKeyString);
  }

  // Retrieves name (full path) of an API key using the API key string.
  public static void lookupApiKey(String apiKeyString) throws IOException {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `apiKeysClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (ApiKeysClient apiKeysClient = ApiKeysClient.create()) {

      // Initialize the lookup request and set the API key string.
      LookupKeyRequest lookupKeyRequest = LookupKeyRequest.newBuilder()
          .setKeyString(apiKeyString)
          .build();

      // Make the request and obtain the response.
      LookupKeyResponse response = apiKeysClient.lookupKey(lookupKeyRequest);

      System.out.printf("Successfully retrieved the API key name: %s", response.getName());
    }
  }
}

Python

이 샘플을 실행하려면 API 키 클라이언트 라이브러리를 설치해야 합니다.


from google.cloud import api_keys_v2

def lookup_api_key(api_key_string: str) -> None:
    """
    Retrieves name (full path) of an API key using the API key string.

    TODO(Developer):
    1. Before running this sample,
      set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
    2. Make sure you have the necessary permission to view API keys.

    Args:
        api_key_string: API key string to retrieve the API key name.
    """

    # Create the API Keys client.
    client = api_keys_v2.ApiKeysClient()

    # Initialize the lookup request and set the API key string.
    lookup_key_request = api_keys_v2.LookupKeyRequest(
        key_string=api_key_string,
        # Optionally, you can also set the etag (version).
        # etag=etag,
    )

    # Make the request and obtain the response.
    lookup_key_response = client.lookup_key(lookup_key_request)

    print(f"Successfully retrieved the API key name: {lookup_key_response.name}")

REST

lookupKey 메서드를 사용하여 키 문자열에서 프로젝트 ID를 가져옵니다.

curl -X GET \
-H "Authorization: Bearer $(gcloud auth print-access-token)" \
-H "Content-Type: application/json; charset=utf-8" \
"https://apikeys.googleapis.com/v2/keys:lookupKey?keyString=KEY_STRING"

API 키 삭제 취소

실수로 API 키를 삭제한 경우 키를 삭제한 후 30일 이내에 해당 키를 삭제 취소(복원)할 수 있습니다. 30일이 지나면 API 키를 삭제 취소할 수 없습니다.

콘솔

  1. Google Cloud console에서 사용자 인증 정보 페이지로 이동합니다.

    사용자 인증 정보로 이동

  2. 삭제된 사용자 인증 정보 복원을 클릭합니다.

  3. 삭제 취소할 삭제된 API 키를 찾고 복원을 클릭합니다.

    API 키를 삭제 취소하면 적용되는 데 몇 분 정도 걸릴 수 있습니다. 적용된 후에는 삭제되지 않은 API 키가 API 키 목록에 표시됩니다.

gcloud

  1. 삭제 취소하려는 키의 ID를 가져옵니다.

    ID는 표시 이름 또는 키 문자열과 같지 않습니다. gcloud services api-keys list --show-deleted 명령어를 사용하여 프로젝트의 삭제된 키를 나열해서 ID를 가져올 수 있습니다.

  2. gcloud beta services api-keys undelete 명령어를 사용하여 API 키를 삭제 취소합니다.

    gcloud beta services api-keys undelete KEY_ID
    

    다음 값을 바꿉니다.

    • KEY_ID: 삭제 취소하려는 키의 ID입니다.

REST

  1. 삭제 취소하려는 키의 ID를 가져옵니다.

    ID는 표시 이름 또는 키 문자열과 같지 않습니다. showDeleted 쿼리 매개변수를 true로 설정하고 keys.list 메서드를 사용하여 ID를 가져올 수 있습니다. 키 ID는 응답의 uid 필드에 나열됩니다.

    PROJECT_ID를 Google Cloud 프로젝트 ID 또는 이름으로 바꿉니다.

    curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys?showDeleted=true"
    
  2. 삭제 취소 메소드를 사용하여 API 키를 삭제 취소합니다.

    curl -X POST \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    "https://apikeys.googleapis.com/v2/projects/PROJECT_ID/locations/global/keys/KEY_ID:undelete"
    

    이 요청은 장기 실행 작업을 반환합니다. 작업이 완료되는 시간을 확인하고 작업 상태를 가져오려면 작업을 폴링해야 합니다.

    다음 값을 바꿉니다.

    • PROJECT_ID: Google Cloud 프로젝트 ID 또는 이름입니다.
    • KEY_ID: 제한하려는 키의 ID입니다.

장기 실행 작업 폴링

API 키 API 메서드에는 장기 실행 작업이 사용됩니다. REST API를 사용하여 API 키를 만들고 관리하는 경우 초기 메서드 요청에서 작업 객체가 반환됩니다. 작업 이름을 사용하여 장기 실행 작업을 폴링합니다. 장기 실행 요청이 완료될 때 작업을 폴링하면 장기 실행 요청에서 데이터가 반환됩니다.

장기 실행 API 키 API 작업을 폴링하려면 operations.get 메서드를 사용합니다.

OPERATION_NAME을 장기 실행 작업으로 반환된 작업 이름으로 바꿉니다. 예를 들면 operations/akmf.p7-358517206116-cd10a88a-7740-4403-a8fd-979f3bd7fe1c입니다.

curl -X GET \
    -H "Authorization: Bearer $(gcloud auth print-access-token)" \
    -H "Content-Type: application/json; charset=utf-8" \
    "https://apikeys.googleapis.com/v2/OPERATION_NAME"

API 키 제한

프로젝트당 최대 300개까지 API 키를 만들 수 있습니다. 이 한도는 시스템 한도이며 할당량 증가 요청을 사용하여 변경될 수 없습니다.

API 키가 더 필요하면 하나를 초과하는 프로젝트를 사용해야 합니다.

다음 단계