使用服務帳戶

服務帳戶是一種 Google 帳戶類型,可供應用程式使用 透過 OAuth 2.0 以程式化方式存取 Google API。這不需要 人工授權,改為使用只有您的應用程式 資源存取權

進一步瞭解服務帳戶前,建議先考量 強烈建議使用 OAuth 2.0 安裝版應用程式流程。雖然 這個流程需要手動使用者互動才能授權您的應用程式, 這個步驟只需執行一次,且請勿在正式環境中執行。 這個流程產生的更新權杖永遠不會過期,可以快取並 也能用來產生 不必與使用者互動

還在閱讀嗎?好的,您可以在以下任一位置使用服務帳戶 方式:

  • 建立多媒體和已連結 Google 影片廣告 新建立的服務帳戶在這個情境中,您的服務帳戶運作一切正常 您可透過使用者帳戶存取所有夥伴和廣告主 佈建了使用者 ID因此我們建議您以這種方式使用服務 您的多媒體廣告和帳戶Video 360。
  • 使用全網域委派功能,代表以下人士提出要求: 更多多媒體和已連結至 G Suite 帳戶的 Video 360 使用者 網域。在此情況下,您必須擁有目標網域的管理員權限。 如需 G Suite 和/或網域設定的相關說明,請參閱 G Suite 支援頁面

必要條件

如要使用已連結至 Display &Video 360 的服務帳戶Video 360 使用者,選取 如要使用全網域委派功能, 選取「Delegation」分頁標籤。

DV360 使用者

您必須擁有多媒體和已連結至服務帳戶的 Video 360 使用者。

委派

  1. 您需要擁有系統管理員權限,可以存取註冊的網域 G Suite
  2. 您必須有一或多個多媒體和已連結至帳戶的 Video 360 使用者 登入 Google 帳戶。連結至以下帳戶的使用者: 其他網域 (例如 gmail.com) 不能使用。

設定及使用服務帳戶

DV360 使用者

  1. Google API 控制台。

  2. 連結螢幕和使用服務帳戶電子郵件地址的 Video 360 使用者 如先前步驟所述 在「多媒體與」頁面中管理使用者Video 360 說明中心 文章。

  3. 如要在應用程式中實作伺服器對伺服器 OAuth 2.0 流程,請使用 建立新的服務帳戶詳情請參閱 examples 一節。

委派

  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 流程,請使用 建立新的服務帳戶詳情請參閱 examples 一節。請記得,你需要提供 假冒,且必須隸屬於您服務的網域 帳戶在上一個步驟中已委派全網域授權。

如需 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)

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