使用服务帐号

服务帐号是一种 Google 帐号,可供应用通过 OAuth 2.0 以编程方式访问 Google API。它不需要人工授权,但需要使用只有您的应用可以访问的密钥文件。

在详细了解服务帐号之前,请考虑更简单、强烈推荐的 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. 您必须将一个或多个 Display & Video 360 用户关联到您注册 G Suite 的网域中的帐号。无法使用与其他网域(例如 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)

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