서비스 계정 사용

서비스 계정은 애플리케이션에서 사용할 수 있는 Google 계정 유형입니다. OAuth 2.0을 통해 프로그래매틱 방식으로 Google API에 액세스할 수 있습니다. 이때 사용자의 애플리케이션에서만 사용할 수 있는 키 파일을 대신 사용합니다. 액세스할 수 있습니다

서비스 계정에 대해 자세히 읽기 전에 간단하면서도 더 많은 계정을 고려하세요. OAuth 2.0이 설치된 애플리케이션 흐름을 적극 권장합니다. 동안 이 흐름에서는 애플리케이션을 승인하기 위해 수동 사용자 상호작용이 필요합니다. 이 단계는 한 번만 수행해야 하며 프로덕션 환경에서 수행할 필요가 없습니다. 이 흐름에서 생성된 갱신 토큰은 만료되지 않으며 캐시될 수 있습니다. 배포되며, 다른 환경에서 액세스 토큰을 생성하는 데 수요를 창출할 수 있습니다.

아직 읽고 계시나요? 다음 중 하나에서 서비스 계정을 사용할 수 있습니다. 있습니다.

  • 디스플레이 및 동영상 360 사용자에게 서비스 계정을 만들 수 있습니다 이 시나리오에서 서비스 계정은 파트너 및 광고주 계정에 액세스하여 사용자 프로비저닝입니다. 서비스를 사용하는 데 선호되는 방법입니다. 계정이 있는 캠페인 및 동영상 360
  • 도메인 전체 위임을 사용하여 도메인 1개 이상을 대신하여 요청합니다. 기타 디스플레이 및 G Suite의 계정에 연결된 Video 360 사용자 있습니다. 이 경우 대상 도메인에 대한 관리자 액세스 권한이 있어야 합니다. G Suite 또는 도메인 구성에 관한 도움말은 다음을 참고하세요. G Suite 지원 페이지

기본 요건

Display &Video 360에 연결된 서비스 계정을 Video 360 사용자의 경우 DV360 사용자 탭으로 이동하세요. 도메인 전체 위임을 사용하려면 다음 단계를 따르세요. 위임 탭을 선택합니다.

DV360 사용자

디스플레이 및 Video 360 사용자가 서비스 계정에 연결되어 있습니다.

위임

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

서비스 계정 구성 및 사용

DV360 사용자

  1. 서비스 계정 키를 Google API 콘솔에서 제공됩니다.

  2. 디스플레이 연결 및 서비스 계정 이메일이 있는 Video 360 사용자 이전 단계에서 얻은 Display &Video 360에서 사용자 관리 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 지원 페이지에서 확인할 수 있습니다.

자바

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)

PHP

/**
 * 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;
    }
}