서비스 계정 사용

서비스 계정은 애플리케이션에서 OAuth 2.0을 통해 프로그래매틱 방식으로 Google API에 액세스하는 데 사용할 수 있는 Google 계정 유형입니다. 여기에는 사람의 승인이 필요하지 않으며 대신 내 애플리케이션만 액세스할 수 있는 키 파일이 사용됩니다.

서비스 계정에 대해 자세히 알아보기 전에 더 간단하고 권장되는 OAuth 2.0 설치 애플리케이션 흐름을 살펴보세요. 이 흐름에서는 애플리케이션을 승인하는 수동 사용자 상호작용이 필요하지만 이 단계는 한 번만 수행하면 되며 프로덕션 환경에서 수행할 필요는 없습니다. 이 흐름에서 생성된 갱신 토큰은 만료되지 않고 캐시되어 다른 환경에 배포할 수 있으며 사용자 상호작용 없이 주문형 액세스 토큰을 생성하는 데 사용할 수 있습니다.

아직 읽기 중이신가요? 서비스 계정은 다음 중 한 가지 방법으로 사용할 수 있습니다.

  • 서비스 계정과 연결된 Display & Video 360 사용자를 만듭니다. 이 시나리오에서는 서비스 계정이 일반 사용자 계정처럼 작동하며 사용자가 프로비저닝된 모든 파트너 및 광고주에 액세스할 수 있습니다. 이는 Display & Video 360에서 서비스 계정을 사용할 때 권장되는 방법입니다.
  • 도메인 전체 위임을 사용하여 G Suite 도메인의 계정에 연결된 한 명 이상의 Display & Video 360 사용자를 대신하여 요청합니다. 이 경우 대상 도메인에 대한 관리자 액세스 권한이 있어야 합니다. G Suite 또는 도메인 구성에 대한 도움말은 G Suite 지원 페이지를 참조하세요.

기본 요건

Display & Video 360 사용자와 연결된 서비스 계정을 사용하려면 아래의 DV360 사용자 탭을 선택하세요. 도메인 전체 위임을 사용하려면 위임 탭을 선택합니다.

DV360 사용자

서비스 계정에 연결된 Display & Video 360 사용자가 있어야 합니다.

위임

  1. G Suite에 등록된 도메인에 대한 관리자 액세스 권한이 있어야 합니다.
  2. G Suite에 등록된 도메인의 계정에 연결된 Display & Video 360 사용자가 한 명 이상 있어야 합니다. 다른 도메인의 계정에 연결된 사용자 (예: gmail.com)는 사용할 수 없습니다.

서비스 계정 구성 및 사용

DV360 사용자

  1. Google API 콘솔에서 서비스 계정 키를 생성합니다.

  2. Display & Video 360의 사용자 관리 고객센터 도움말에 설명된 대로 Display & Video 360 사용자를 이전 단계에서 받은 서비스 계정 이메일과 연결합니다.

  3. 새로 만든 서비스 계정을 사용하여 애플리케이션에서 서버 간 OAuth 2.0 흐름을 구현합니다. 자세한 내용은 섹션을 참고하세요.

위임

  1. Google API 콘솔에서 서비스 계정 키를 생성합니다.

  2. 이 서비스 계정에 도메인 전체 권한을 위임하여 도메인 내의 사용자를 가장할 수 있도록 합니다. 메시지가 표시되면 다음 API 범위를 입력합니다.

    범위 의미
    https://www.googleapis.com/auth/display-video 읽기/쓰기 액세스
    https://www.googleapis.com/auth/display-video-user-management users 서비스에 대한 읽기/쓰기 액세스 권한입니다. 서비스 계정 사용자만 사용할 수 있습니다.

  3. 새로 만든 서비스 계정을 사용하여 애플리케이션에서 서버 간 OAuth 2.0 흐름을 구현합니다. 자세한 내용은 섹션을 참고하세요. 가장할 계정을 제공해야 하며, 이 계정은 이전 단계에서 서비스 계정이 도메인 전체 권한을 위임받은 도메인에 속해야 합니다.

G Suite 또는 도메인 구성에 대한 도움말은 G Suite 지원 페이지를 참조하세요.

Java

import com.google.api.client.auth.oauth2.Credential;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.services.displayvideo.v3.DisplayVideo;
import com.google.api.services.displayvideo.v3.DisplayVideoScopes;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableSet;
import java.io.FileInputStream;

/**
 * This example demonstrates how to authenticate using a service account.
 */
public class AuthenticateUsingServiceAccount {
  // Path to a JSON file containing service account credentials for this application. This file can
  // be downloaded from the Credentials tab on the Google API Console.
  private static final String PATH_TO_JSON_FILE = "ENTER_PATH_TO_CLIENT_SECRETS_HERE";

  /**
   * An optional Google account email to impersonate. Only applicable to service accounts which have
   * enabled domain-wide delegation and wish to make API requests on behalf of an account within
   * their domain. Setting this field will not allow you to impersonate a user from a domain you
   * don't own (e.g., gmail.com).
   */
  private static final String EMAIL_TO_IMPERSONATE = "";

  // The OAuth 2.0 scopes to request.
  private static final ImmutableSet OAUTH_SCOPES =
      ImmutableSet.copyOf(DisplayVideoScopes.all());

  private static Credential getServiceAccountCredential(
      String pathToJsonFile, String emailToImpersonate) throws Exception {
    // Generate a credential object from the specified JSON file.
    GoogleCredential credential = GoogleCredential.fromStream(new FileInputStream(pathToJsonFile));

    // Update the credential object with appropriate scopes and impersonation info (if applicable).
    if (Strings.isNullOrEmpty(emailToImpersonate)) {
      credential = credential.createScoped(OAUTH_SCOPES);
    } else {
      credential =
          new GoogleCredential.Builder()
              .setTransport(credential.getTransport())
              .setJsonFactory(credential.getJsonFactory())
              .setServiceAccountId(credential.getServiceAccountId())
              .setServiceAccountPrivateKey(credential.getServiceAccountPrivateKey())
              .setServiceAccountScopes(OAUTH_SCOPES)
              // Set the email of the user you are impersonating (this can be yourself).
              .setServiceAccountUser(emailToImpersonate)
              .build();
    }

    return credential;
  }

  public static void main(String[] args) throws Exception {
    // Build service account credential.
    Credential credential = getServiceAccountCredential(PATH_TO_JSON_FILE, EMAIL_TO_IMPERSONATE);

    // Create a DisplayVideo service instance.
    //
    // Note: application name below should be replaced with a value that identifies your
    // application. Suggested format is "MyCompany-ProductName/Version.MinorVersion".
    DisplayVideo service =
        new DisplayVideo.Builder(credential.getTransport(), credential.getJsonFactory(), credential)
            .setApplicationName("displayvideo-java-service-acct-sample")
            .build();

    // Make API requests.
  }
}

Python

"""This example demonstrates how to authenticate using a service account.

An optional Google account email to impersonate may be specified as follows:
    authenticate_using_service_account.py <path_to_json_file> -i <email>

This optional flag only applies to service accounts which have domain-wide
delegation enabled and wish to make API requests on behalf of an account
within that domain. Using this flag will not allow you to impersonate a
user from a domain you don't own (e.g., gmail.com).
"""

import argparse
import sys

from googleapiclient import discovery
import httplib2
from oauth2client import client
from oauth2client import tools
from oauth2client.service_account import ServiceAccountCredentials

# Declare command-line flags.
argparser = argparse.ArgumentParser(add_help=False)
argparser.add_argument(
    'path_to_service_account_json_file',
    help='Path to the service account JSON file to use for authenticating.')
argparser.add_argument(
    '-i',
    '--impersonation_email',
    help='Google account email to impersonate.')

API_NAME = 'displayvideo'
API_VERSION = 'v3'
API_SCOPES = ['https://www.googleapis.com/auth/display-video']


def main(argv):
  # Retrieve command line arguments.
  parser = argparse.ArgumentParser(
      description=__doc__,
      formatter_class=argparse.RawDescriptionHelpFormatter,
      parents=[tools.argparser, argparser])
  flags = parser.parse_args(argv[1:])

  # Authenticate using the supplied service account credentials
  http = authenticate_using_service_account(
      flags.path_to_service_account_json_file,
      flags.impersonation_email)

  # Build a service object for interacting with the API.
  service = discovery.build(API_NAME, API_VERSION, http=http)

  # Make API requests.

def authenticate_using_service_account(path_to_service_account_json_file,
                                       impersonation_email):
  """Authorizes an httplib2.Http instance using service account credentials."""
  # Load the service account credentials from the specified JSON keyfile.
  credentials = ServiceAccountCredentials.from_json_keyfile_name(
      path_to_service_account_json_file,
      scopes=API_SCOPES)

  # Configure impersonation (if applicable).
  if impersonation_email:
    credentials = credentials.create_delegated(impersonation_email)

  # Use the credentials to authorize an httplib2.Http instance.
  http = credentials.authorize(httplib2.Http())

  return http


if __name__ == '__main__':
  main(sys.argv)

2,399필리핀

/**
 * This example demonstrates how to authenticate using a service account.
 *
 * The optional flag email parameter only applies to service accounts which have
 * domain-wide delegation enabled and wish to make API requests on behalf of an
 * account within that domain. Using this flag will not allow you to impersonate
 * a user from a domain that you don't own (e.g., gmail.com).
 */
class AuthenticateUsingServiceAccount
{
    // The OAuth 2.0 scopes to request.
    private static $OAUTH_SCOPES = [Google_Service_DisplayVideo::DISPLAY_VIDEO];

    public function run($pathToJsonFile, $email = null)
    {
        // Create an authenticated client object.
        $client = $this->createAuthenticatedClient($pathToJsonFile, $email);

        // Create a Dfareporting service object.
        $service = new Google_Service_DisplayVideo($client);

        // Make API requests.
    }

    private function createAuthenticatedClient($pathToJsonFile, $email)
    {
        // Create a Google_Client instance.
        //
        // Note: application name should be replaced with a value that identifies
        // your application. Suggested format is "MyCompany-ProductName".
        $client = new Google_Client();
        $client->setApplicationName('PHP service account sample');
        $client->setScopes(self::$OAUTH_SCOPES);

        // Load the service account credentials.
        $client->setAuthConfig($pathToJsonFile);

        // Configure impersonation (if applicable).
        if (!is_null($email)) {
            $client->setSubject($email);
        }

        return $client;
    }
}