Geocoding API: API 키 가져오기

참고: Google Maps Platform 프리미엄 플랜은 신규 가입이 불가능하며 신규 고객에게 제공되지 않습니다.

인증 방식 선택

Google Maps Platform을 사용하려면 API 키 또는 클라이언트 ID와 디지털 서명을 사용하여 요청을 인증해야 합니다.

인증 방법은 라이선스를 기준으로 선택합니다.

  • 프리미엄 요금제를 이용하는 고객은 API 키 또는 클라이언트 ID와 디지털 서명을 사용할 수 있습니다.
  • 이전 라이선스를 보유한 고객은 클라이언트 ID와 디지털 서명을 사용해야 합니다.

사용할 인증 방법을 결정할 때는 다음 사항을 고려하세요.

  • API 키를 사용한 인증(프리미엄 요금제)
    API 키를 사용하여 요청을 인증하면 다음 작업이 가능합니다.
    • Google Cloud Console의 API 페이지에서 모든 API를 관리합니다.
    • Cloud Console의 API 페이지에서 실시간 사용 데이터와 30일 분량의 과거 사용 데이터에 액세스합니다.
    • channel 매개변수를 요청에 추가하여 더 자세한 사용량 확인
    • Google Cloud Console에서 30일 이상 지난 데이터가 포함된 사용량 보고서를 조회합니다.
  • 클라이언트 ID와 디지털 서명을 사용한 인증(프리미엄 요금제 또는 이전 라이선스)
    클라이언트 ID와 디지털 서명을 사용하여 요청을 인증하면 다음 작업이 가능합니다.
    • channel 매개변수를 요청에 추가하여 더 자세한 사용량 확인
    • Cloud Console에서 30일 이상 지난 데이터가 포함된 사용량 보고서를 조회합니다.
    • Maps JavaScript API에 지도 애널리틱스 도구 사용

자세한 내용은 프리미엄 요금제 고객이 사용할 수 있는 보고서를 참고하세요.

API 키를 사용한 인증

API 키 가져오기

API 키는 사용 및 결제 목적으로 프로젝트와 관련된 요청을 인증하는 데 사용되는 고유 식별자입니다.

API 키를 가져오는 방법은 다음과 같습니다.

  1. Cloud Console의 프로젝트 선택기 페이지에서 API 키를 추가할 Google Cloud 프로젝트를 선택하거나 만듭니다.

    프로젝트 선택기 페이지로 이동

    참고: 요금제의 모든 기능을 이용하려면 프리미엄 고객은 프리미엄 계정과 연결된 프로젝트를 사용해야 합니다. 라이선스를 구매할 때 프리미엄 애셋의 이름이 gme-[company] > proj-[number] ([type]) 형식으로 제공됩니다. 올바른 프로젝트에 액세스하고 있는지 확인하려면 console.cloud.google.com/project/number를 사용하여 프로젝트 소유자로 Console에 로그인하세요(number를 프로젝트 번호로 바꾸세요). 프로젝트 소유자는 환영 메일에서 찾을 수 있습니다.

  2. Google Maps Platform > 사용자 인증 정보 페이지로 이동합니다.

    사용자 인증 정보 페이지로 이동하기

  3. 사용자 인증 정보 페이지에서 사용자 인증 정보 만들기 > API 키를 클릭합니다.
    API 키 생성 완료 대화상자에 새로 만든 API 키가 표시됩니다.
  4. 닫기를 클릭합니다.
    새 API 키는 사용자 인증 정보 페이지에서 API 키 아래에 표시됩니다.
    (프로덕션에 사용하기 전에 API 키를 제한하세요)

요청에 API 키 추가

모든 Google Maps Platform 요청에 API 키를 포함해야 합니다. 다음 예에서 YOUR_API_KEY를 API 키로 바꾸세요.

https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&key=YOUR_API_KEY

HTTPS는 API 키를 사용하는 요청에 필요하며 클라이언트 ID를 사용하는 요청에 권장됩니다. 사용자의 위치와 같은 민감한 사용자 데이터를 요청에 포함하는 애플리케이션에도 HTTPS가 필요합니다.

API 키 제한

API 키를 제한하면 승인된 요청만 API 키로 실행되기 때문에 애플리케이션 보안이 강화됩니다. 안내에 따라 API 키에 대한 제한을 설정하시기 바랍니다. 자세한 내용은 API 키 권장사항을 참고하세요.

API 키를 제한하는 방법은 다음과 같습니다.

  1. Google Maps Platform > 사용자 인증 정보 페이지로 이동합니다.

    사용자 인증 정보 페이지로 이동하기

  2. 제한을 설정할 API 키를 선택합니다. API 키 속성 페이지가 나타납니다.
  3. 키 제한사항에서 다음 제한사항을 설정합니다.
    • 애플리케이션 제한:
      1. 제공하는 웹 서버 IP 주소 목록에서 요청을 수락하려면 애플리케이션 제한사항 목록에서 IP 주소(웹 서버, 크론 작업 등)를 선택합니다.
      2. CIDR 표기법(예: 192.168.0.0/22)을 사용하여 IPv4나 IPv6 주소 하나 또는 서브넷을 지정합니다. 다른 항목을 입력해야 하는 경우 이전 항목을 추가한 후 새 상자가 표시됩니다.
    • API 제한:
      1. 키 제한을 클릭합니다.
      2. API 선택 드롭다운에서 Google Maps Platform을 선택합니다. Google Maps Platform이 표시되지 않으면 사용 설정해야 합니다.
  4. 변경사항을 적용하려면 저장을 클릭합니다.

클라이언트 ID 및 디지털 서명을 사용한 인증

Google Maps Platform 프리미엄 플랜 라이선스를 구매하면 Google로부터 클라이언트 ID와 (고유한 디지털 서명을 생성하는 데 사용할 수 있는) 비공개 암호화 키가 포함된 환영 이메일을 받게 됩니다.

아래의 코드 예에서는 클라이언트 ID와 고유한 디지털 서명을 전달해야 하는 clientsignature 매개변수를 보여줍니다.

    https://maps.googleapis.com/maps/api/geocode/json
      ?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA
      &client=YOUR_CLIENT_ID
      &signature=SIGNATURE
  • YOUR_CLIENT_ID를 환영 이메일에 포함된 클라이언트 ID로 바꾸세요.

    클라이언트 ID는 gme- 문자로 시작합니다.

  • SIGNATURE를 고유한 디지털 서명으로 바꾸세요(디지털 서명 생성 참고).

참고:

  • 클라이언트 ID 및 디지털 서명을 사용하여 Google Maps Platform을 인증할 때 channel 매개변수를 사용하여 자세한 사용량 보고서를 받을 수도 있습니다. 자세한 내용은 프리미엄 요금제 보고 개요를 참고하세요.
  • 이전에 인증에 API 키를 사용하다가 클라이언트 ID로 전환하는 경우 요청에서 key 매개변수를 삭제해야 합니다. Google 지도 API 웹 서비스는 클라이언트 ID와 API 키를 둘 다 사용하여 생성된 요청을 거부합니다.

디지털 서명 생성

Google Maps Platform 프리미엄 플랜 고객의 Geocoding API 요청에는 환영 이메일에 제공된 개인 암호화 키를 사용하여 생성할 수 있는 디지털 signature가 필요합니다(개인 암호화 키에 대한 추가 정보 참고).

아래 단계에 따라 요청의 디지털 서명을 생성합니다.

  1. 서명 없이 요청 URL을 생성하고 client 매개변수를 포함합니다. 표준이 아닌 모든 문자는 URL로 인코딩해야 합니다.

    https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&client=clientID

    참고: 모든 Google 서비스에는 ASCII가 암시적으로 포함된 UTF-8 문자 인코딩이 필요합니다. 애플리케이션이 다른 문자 집합을 사용하여 실행되는 경우 UTF-8을 사용하여 URL을 구성하고 올바로 URL 인코딩해야 합니다.

  2. 요청에서 도메인 부분을 떼어내고 경로와 쿼리만 남겨둡니다.

    /maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&client=clientID

  3. 수정된 URL용 Base64로 인코딩된 비공개 키를 가져오고 HMAC-SHA1 알고리즘을 사용하여 위의 URL에 서명합니다. 이 키를 원래의 바이너리 형식으로 디코딩해야 할 수도 있습니다. 대부분의 암호 라이브러리에서는 결과로 얻은 서명이 바이너리 형식입니다.

    참고: 수정된 URL용 Base64는 표준 Base64의 +/ 문자를 각각 -_로 바꾸므로 이 Base64 서명은 더 이상 URL로 인코딩하지 않아도 됩니다.

  4. 수정된 URL용 Base64를 사용하여 결과 바이너리 서명을 인코딩하여 이 서명을 URL 내에서 전달할 수 있는 형식으로 변환합니다.

  5. 이 서명을 signature 매개변수 내 URL에 추가합니다.

    https://maps.googleapis.com/maps/api/geocode/json?address=1600+Amphitheatre+Parkway,+Mountain+View,+CA&client=clientID&signature=base64signature

참고:

  • 고유한 서명을 사용하면 클라이언트 ID를 사용하여 요청을 생성하는 사이트에 요청 생성 권한이 있는지를 서버에서 확인할 수 있습니다. 또한 서명은 URL마다 고유하므로 클라이언트 ID를 사용하는 요청은 반드시 새 서명을 생성해야 수정할 수 있습니다.
  • 잘못된 서명으로 Geocoding API에 액세스하려고 하면 HTTP 403 (Forbidden) 오류가 발생합니다. URL 서명을 사용하도록 애플리케이션을 변환하는 경우 서명을 테스트하여 올바른 요청이 시작되는지 확인해야 합니다. 먼저 원본 URL이 올바른지 테스트하고 올바른 서명이 생성되는지도 테스트해야 합니다.
  • 서버 측 코드를 사용하여 URL 서명을 구현하는 방법은 URL 서명 샘플 코드를 참고하세요.

지금 URL에 서명하려면 아래에 URL과 URL 서명 비밀번호를 입력하세요. URL은 위의 1단계에 설명된 형식이고 URL로 인코딩되어야 합니다.

URL 서명 샘플 코드

다음 섹션에서는 서버 측 코드를 사용하는 URL 서명을 구현하는 방법을 보여줍니다. 암호화 키가 사용자에게 노출되지 않도록 하려면 항상 서버 측에서 URL에 서명해야 합니다.

Python

아래의 예에서는 표준 Python 라이브러리를 사용하여 URL에 서명합니다. (코드 다운로드)

#!/usr/bin/python
# -*- coding: utf-8 -*-
""" Signs a URL using a URL signing secret """

import hashlib
import hmac
import base64
import urllib.parse as urlparse

def sign_url(input_url=None, secret=None):
    """ Sign a request URL with a URL signing secret.
      Usage:
      from urlsigner import sign_url
      signed_url = sign_url(input_url=my_url, secret=SECRET)
      Args:
      input_url - The URL to sign
      secret    - Your URL signing secret
      Returns:
      The signed request URL
  """

    if not input_url or not secret:
        raise Exception("Both input_url and secret are required")

    url = urlparse.urlparse(input_url)

    # We only need to sign the path+query part of the string
    url_to_sign = url.path + "?" + url.query

    # Decode the private key into its binary format
    # We need to decode the URL-encoded private key
    decoded_key = base64.urlsafe_b64decode(secret)

    # Create a signature using the private key and the URL-encoded
    # string using HMAC SHA1. This signature will be binary.
    signature = hmac.new(decoded_key, str.encode(url_to_sign), hashlib.sha1)

    # Encode the binary signature into base64 for use within a URL
    encoded_signature = base64.urlsafe_b64encode(signature.digest())

    original_url = url.scheme + "://" + url.netloc + url.path + "?" + url.query

    # Return signed URL
    return original_url + "&signature=" + encoded_signature.decode()

if __name__ == "__main__":
    input_url = input("URL to Sign: ")
    secret = input("URL signing secret: ")
    print("Signed URL: " + sign_url(input_url, secret))

자바

아래 예에서는 JDK 1.8부터 사용 가능한 java.util.Base64 클래스를 사용합니다. 이전 버전의 경우 Apache Commons나 비슷한 제품을 사용해야 할 수도 있습니다. (코드 다운로드)

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;  // JDK 1.8 only - older versions may need to use Apache Commons or similar.
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.net.URL;
import java.io.BufferedReader;
import java.io.InputStreamReader;

public class UrlSigner {

  // Note: Generally, you should store your private key someplace safe
  // and read them into your code

  private static String keyString = "YOUR_PRIVATE_KEY";

  // The URL shown in these examples is a static URL which should already
  // be URL-encoded. In practice, you will likely have code
  // which assembles your URL from user or web service input
  // and plugs those values into its parameters.
  private static String urlString = "YOUR_URL_TO_SIGN";

  // This variable stores the binary key, which is computed from the string (Base64) key
  private static byte[] key;

  public static void main(String[] args) throws IOException,
    InvalidKeyException, NoSuchAlgorithmException, URISyntaxException {

    BufferedReader input = new BufferedReader(new InputStreamReader(System.in));

    String inputUrl, inputKey = null;

    // For testing purposes, allow user input for the URL.
    // If no input is entered, use the static URL defined above.
    System.out.println("Enter the URL (must be URL-encoded) to sign: ");
    inputUrl = input.readLine();
    if (inputUrl.equals("")) {
      inputUrl = urlString;
    }

    // Convert the string to a URL so we can parse it
    URL url = new URL(inputUrl);

    // For testing purposes, allow user input for the private key.
    // If no input is entered, use the static key defined above.
    System.out.println("Enter the Private key to sign the URL: ");
    inputKey = input.readLine();
    if (inputKey.equals("")) {
      inputKey = keyString;
    }

    UrlSigner signer = new UrlSigner(inputKey);
    String request = signer.signRequest(url.getPath(),url.getQuery());

    System.out.println("Signed URL :" + url.getProtocol() + "://" + url.getHost() + request);
  }

  public UrlSigner(String keyString) throws IOException {
    // Convert the key from 'web safe' base 64 to binary
    keyString = keyString.replace('-', '+');
    keyString = keyString.replace('_', '/');
    System.out.println("Key: " + keyString);
    // Base64 is JDK 1.8 only - older versions may need to use Apache Commons or similar.
    this.key = Base64.getDecoder().decode(keyString);
  }

  public String signRequest(String path, String query) throws NoSuchAlgorithmException,
    InvalidKeyException, UnsupportedEncodingException, URISyntaxException {

    // Retrieve the proper URL components to sign
    String resource = path + '?' + query;

    // Get an HMAC-SHA1 signing key from the raw key bytes
    SecretKeySpec sha1Key = new SecretKeySpec(key, "HmacSHA1");

    // Get an HMAC-SHA1 Mac instance and initialize it with the HMAC-SHA1 key
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(sha1Key);

    // compute the binary signature for the request
    byte[] sigBytes = mac.doFinal(resource.getBytes());

    // base 64 encode the binary signature
    // Base64 is JDK 1.8 only - older versions may need to use Apache Commons or similar.
    String signature = Base64.getEncoder().encodeToString(sigBytes);

    // convert the signature to 'web safe' base 64
    signature = signature.replace('+', '-');
    signature = signature.replace('/', '_');

    return resource + "&signature=" + signature;
  }
}

Node JS

아래 예에서는 네이티브 노드 모듈을 사용하여 URL에 서명합니다. (코드 다운로드)

'use strict'

const crypto = require('crypto');
const url = require('url');

/**
 * Convert from 'web safe' base64 to true base64.
 *
 * @param  {string} safeEncodedString The code you want to translate
 *                                    from a web safe form.
 * @return {string}
 */
function removeWebSafe(safeEncodedString) {
  return safeEncodedString.replace(/-/g, '+').replace(/_/g, '/');
}

/**
 * Convert from true base64 to 'web safe' base64
 *
 * @param  {string} encodedString The code you want to translate to a
 *                                web safe form.
 * @return {string}
 */
function makeWebSafe(encodedString) {
  return encodedString.replace(/\+/g, '-').replace(/\//g, '_');
}

/**
 * Takes a base64 code and decodes it.
 *
 * @param  {string} code The encoded data.
 * @return {string}
 */
function decodeBase64Hash(code) {
  // "new Buffer(...)" is deprecated. Use Buffer.from if it exists.
  return Buffer.from ? Buffer.from(code, 'base64') : new Buffer(code, 'base64');
}

/**
 * Takes a key and signs the data with it.
 *
 * @param  {string} key  Your unique secret key.
 * @param  {string} data The url to sign.
 * @return {string}
 */
function encodeBase64Hash(key, data) {
  return crypto.createHmac('sha1', key).update(data).digest('base64');
}

/**
 * Sign a URL using a secret key.
 *
 * @param  {string} path   The url you want to sign.
 * @param  {string} secret Your unique secret key.
 * @return {string}
 */
function sign(path, secret) {
  const uri = url.parse(path);
  const safeSecret = decodeBase64Hash(removeWebSafe(secret));
  const hashedSignature = makeWebSafe(encodeBase64Hash(safeSecret, uri.path));
  return url.format(uri) + '&signature=' + hashedSignature;
}

C#

아래 예에서는 기본 System.Security.Cryptography 라이브러리를 사용하여 URL 요청에 서명합니다. 기본 Base64 인코딩을 URL 안전 버전을 구현하도록 변환해야 합니다. (코드 다운로드)

using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;

namespace SignUrl {

  public struct GoogleSignedUrl {

    public static string Sign(string url, string keyString) {
      ASCIIEncoding encoding = new ASCIIEncoding();

      // converting key to bytes will throw an exception, need to replace '-' and '_' characters first.
      string usablePrivateKey = keyString.Replace("-", "+").Replace("_", "/");
      byte[] privateKeyBytes = Convert.FromBase64String(usablePrivateKey);

      Uri uri = new Uri(url);
      byte[] encodedPathAndQueryBytes = encoding.GetBytes(uri.LocalPath + uri.Query);

      // compute the hash
      HMACSHA1 algorithm = new HMACSHA1(privateKeyBytes);
      byte[] hash = algorithm.ComputeHash(encodedPathAndQueryBytes);

      // convert the bytes to string and make url-safe by replacing '+' and '/' characters
      string signature = Convert.ToBase64String(hash).Replace("+", "-").Replace("/", "_");

      // Add the signature to the existing URI.
      return uri.Scheme+"://"+uri.Host+uri.LocalPath + uri.Query +"&signature=" + signature;
    }
  }

  class Program {

    static void Main() {

      // Note: Generally, you should store your private key someplace safe
      // and read them into your code

      const string keyString = "YOUR_PRIVATE_KEY";

      // The URL shown in these examples is a static URL which should already
      // be URL-encoded. In practice, you will likely have code
      // which assembles your URL from user or web service input
      // and plugs those values into its parameters.
      const  string urlString = "YOUR_URL_TO_SIGN";

      string inputUrl = null;
      string inputKey = null;

      Console.WriteLine("Enter the URL (must be URL-encoded) to sign: ");
      inputUrl = Console.ReadLine();
      if (inputUrl.Length == 0) {
        inputUrl = urlString;
      }

      Console.WriteLine("Enter the Private key to sign the URL: ");
      inputKey = Console.ReadLine();
      if (inputKey.Length == 0) {
        inputKey = keyString;
      }

      Console.WriteLine(GoogleSignedUrl.Sign(inputUrl,inputKey));
    }
  }
}

다음과 같은 URL과 비공개 키를 테스트하여 올바른 서명이 생성되는지 확인할 수 있습니다. 이 비공개 키는 테스트 용도로만 사용할 수 있으며 Google 서비스로 유효성이 검사되지 않습니다.

  • URL: https://maps.googleapis.com/maps/api/geocode/json?address=New+York&client=clientID
  • 비공개 키: vNIXE0xscrmjlyV-12Nj_BvUPaw=
  • 서명할 URL 부분: /maps/api/geocode/json?address=New+York&client=clientID
  • 서명: chaRF2hTJKOScPr-RQCEhZbSzIE=
  • 서명된 전체 URL: https://maps.googleapis.com/maps/api/geocode/json?address=New+York&client=clientID&signature=chaRF2hTJKOScPr-RQCEhZbSzIE=

다른 언어로 구현된 예시

다른 언어가 포함된 예는 url-signing 프로젝트를 참고하세요.

비공개 암호화 키에 대해 자세히 알아보기

비공개 암호화 URL 서명 키는 클라이언트 ID와 함께 발급되며 사용자와 Google 사이의 '비밀번호 공유 키'입니다. 이 서명 키는 사용자 전용이며 클라이언트 ID별로 고유합니다. 그러므로 서명 키를 안전하게 보관해야 합니다. 이 키는 요청에 전달하거나 웹사이트에 저장하거나 공개 포럼에 게시해서는 안 됩니다. 이 서명 키를 얻은 사람이 사용자의 신원을 사용하여 요청을 스푸핑할 수 있습니다.

참고: 이 비공개 암호화 서명 키는 Google Cloud Console에서 발급한 API 키와 동일하지 않습니다.

개인 암호화 키를 분실한 경우 Cloud Console에 로그인한 후 지도: 클라이언트 ID 관리를 선택하여 확인하세요.

인증 문제 해결

요청의 형식이 잘못되었거나 잘못된 서명이 포함된 경우 Google Maps Platform에서 HTTP 403 (Forbidden) 오류를 반환합니다.

개별 URL의 문제를 해결하려면 URL 서명 디버거를 사용하세요. 이 도구를 사용하면 애플리케이션이 생성한 URL과 서명의 유효성을 신속하게 검사할 수 있습니다.

또는 프리미엄 플랜 고객의 경우 Cloud Console에 로그인하고 리소스 > Google Maps Platform 프리미엄 플랜 온라인 도구 > 웹 서비스 및 이미지 API용 URL 서명 디버거를 선택하여 개별 URL의 문제를 해결할 수 있습니다.