Sử dụng tài khoản dịch vụ

Tài khoản dịch vụ là một loại Tài khoản Google mà ứng dụng có thể dùng để truy cập vào các API của Google theo cách lập trình thông qua OAuth 2.0. Thao tác này không yêu cầu sự cho phép của con người mà thay vào đó sử dụng một tệp khoá mà chỉ ứng dụng của bạn mới có thể truy cập.

Trước khi đọc thêm về tài khoản dịch vụ, hãy cân nhắc quy trình ứng dụng đã cài đặt OAuth 2.0 đơn giản và được đề xuất nhiều hơn. Mặc dù quy trình này yêu cầu người dùng tương tác theo cách thủ công để cho phép ứng dụng của bạn, nhưng bước này chỉ được thực hiện một lần và không cần thực hiện trong môi trường phát hành chính thức. Mã làm mới do luồng này tạo ra không bao giờ hết hạn, có thể được lưu vào bộ nhớ đệm và triển khai cho nhiều môi trường, đồng thời có thể được dùng để tạo mã truy cập theo yêu cầu mà không cần người dùng phải tương tác.

Bạn vẫn đang đọc? Được rồi, bạn có thể sử dụng tài khoản dịch vụ theo một trong các cách sau:

  • Tạo người dùng Display & Video 360 liên kết với tài khoản dịch vụ của bạn. Trong trường hợp này, tài khoản dịch vụ của bạn sẽ hoạt động như một tài khoản người dùng thông thường và cho phép bạn truy cập vào tất cả các đối tác và nhà quảng cáo mà người dùng đã được cấp phép. Đây là cách ưu tiên để sử dụng tài khoản dịch vụ với Display & Video 360.
  • Sử dụng tính năng uỷ quyền trên toàn miền để đưa ra yêu cầu thay mặt cho một hoặc nhiều người dùng Display & Video 360 được liên kết với các tài khoản thuộc miền G Suite. Trong trường hợp này, bạn phải có quyền quản trị đối với miền đích. Để được trợ giúp về cấu hình G Suite và/hoặc miền, hãy xem trang hỗ trợ G Suite.

Điều kiện tiên quyết

Để sử dụng tài khoản dịch vụ liên kết với người dùng Display & Video 360, hãy chọn thẻ Người dùng DV360 bên dưới. Để sử dụng tính năng uỷ quyền trên toàn miền, hãy chọn thẻ Uỷ quyền.

Người dùng DV360

Bạn phải có một người dùng Display & Video 360 được liên kết với tài khoản dịch vụ của bạn.

Uỷ thác

  1. Bạn phải có quyền quản trị đối với miền đã đăng ký với G Suite.
  2. Bạn phải có một hoặc nhiều người dùng Display & Video 360 được liên kết với các tài khoản trong miền mà bạn đã đăng ký sử dụng G Suite. Bạn không thể sử dụng những người dùng được liên kết với các tài khoản thuộc miền khác (ví dụ: gmail.com).

Định cấu hình và sử dụng tài khoản dịch vụ

Người dùng DV360

  1. Tạo khoá tài khoản dịch vụ trong Bảng điều khiển API của Google.

  2. Liên kết người dùng Display & Video 360 với email tài khoản dịch vụ nhận được ở bước trước như mô tả trong bài viết Quản lý người dùng trong Display & Video 360 trên trung tâm trợ giúp.

  3. Triển khai quy trình OAuth 2.0 từ máy chủ đến máy chủ trong ứng dụng bằng tài khoản dịch vụ mới tạo. Để biết thêm thông tin, hãy xem phần ví dụ.

Uỷ thác

  1. Tạo khoá tài khoản dịch vụ trong Bảng điều khiển API của Google.

  2. Uỷ quyền quyền trên toàn miền cho tài khoản dịch vụ này để cho phép tài khoản mạo danh người dùng trong miền của bạn. Khi được nhắc, hãy cung cấp các phạm vi API sau:

    Phạm vi Ý nghĩa
    https://www.googleapis.com/auth/display-video Quyền đọc/ghi
    https://www.googleapis.com/auth/display-video-user-management Quyền đọc/ghi cho dịch vụ users. Chỉ dành cho người dùng tài khoản dịch vụ.

  3. Triển khai quy trình OAuth 2.0 từ máy chủ đến máy chủ trong ứng dụng bằng tài khoản dịch vụ mới tạo. Để biết thêm thông tin, hãy xem phần ví dụ. Hãy nhớ rằng bạn sẽ cần cung cấp một tài khoản để mạo danh và tài khoản này phải thuộc miền mà tài khoản dịch vụ của bạn đã được uỷ quyền trên toàn miền trong bước trước.

Để được trợ giúp về cấu hình G Suite và / hoặc miền, hãy xem trang trang hỗ trợ G Suite.

Ví dụ

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)

1.199

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