使用客户端库向 Cloud 服务进行身份验证

使用集合让一切井井有条 根据您的偏好保存内容并对其进行分类。

本页面介绍了如何使用客户端库和应用默认凭据访问 Google API。

通过客户端库,您可以更轻松地使用支持的语言访问 Google Cloud API。您可以直接通过向服务器发出原始请求来使用 Google Cloud API,但客户端库可提供简化,从而显著减少您需要编写的代码量。这对于身份验证尤其如此,因为客户端库支持应用默认凭据 (ADC)

客户端库类型

客户端库有两种类型:Cloud 客户端库和 Google API 客户端库。这两种类型都支持应用默认凭据。如需了解详情,请参阅客户端库说明

将应用默认凭据与客户端库搭配使用

如需使用应用默认凭据对应用进行身份验证,您必须先为应用运行的环境设置应用默认凭据。使用客户端库创建客户端时,客户端库会自动检查和使用您提供给 ADC 的凭据,从而向代码使用的 API 进行身份验证。您的应用无需明确对令牌进行身份验证或管理;这些要求由身份验证库自动管理。

示例客户端创建

以下代码示例为 Cloud Storage 服务创建客户端。您的代码可能需要不同的客户端;这些示例仅用于展示如何在无需任何代码来明确进行身份验证的情况下创建客户端并使用它。

您必须先设置 ADC安装 Cloud Storage 客户端库,然后才能运行以下示例。

Java


import com.google.cloud.compute.v1.Instance;
import com.google.cloud.compute.v1.InstancesClient;
import java.io.IOException;

public class AuthenticateImplicitWithAdc {

  public static void main(String[] args) throws IOException {
    // TODO(Developer):
    //  1. Before running this sample,
    //  set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
    //  2. Replace the project variable below.
    //  3. Make sure that the user account or service account that you are using
    //  has the required permissions. For this sample, you must have "compute.instances.list".
    String projectId = "your-google-cloud-project-id";
    authenticateImplicitWithAdc(projectId);
  }

  // When interacting with Google Cloud Client libraries, the library can auto-detect the
  // credentials to use.
  public static void authenticateImplicitWithAdc(String project) throws IOException {

    String zone = "us-central1-a";
    // This snippet demonstrates how to list instances.
    // *NOTE*: Replace the client created below with the client required for your application.
    // Note that the credentials are not specified when constructing the client.
    // Hence, the client library will look for credentials using ADC.
    //
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the `instancesClient.close()` method on the client to safely
    // clean up any remaining background resources.
    try (InstancesClient instancesClient = InstancesClient.create()) {
      // Set the project and zone to retrieve instances present in the zone.
      System.out.printf("Listing instances from %s in %s:", project, zone);
      for (Instance zoneInstance : instancesClient.list(project, zone).iterateAll()) {
        System.out.println(zoneInstance.getName());
      }
      System.out.println("####### Listing instances complete #######");
    }
  }
}

Python


from google.cloud import storage

def authenticate_implicit_with_adc(project_id="your-google-cloud-project-id"):
    """
    When interacting with Google Cloud Client libraries, the library can auto-detect the
    credentials to use.

    // TODO(Developer):
    //  1. Before running this sample,
    //  set up ADC as described in https://cloud.google.com/docs/authentication/external/set-up-adc
    //  2. Replace the project variable.
    //  3. Make sure that the user account or service account that you are using
    //  has the required permissions. For this sample, you must have "storage.buckets.list".
    Args:
        project_id: The project id of your Google Cloud project.
    """

    # This snippet demonstrates how to list buckets.
    # *NOTE*: Replace the client created below with the client required for your application.
    # Note that the credentials are not specified when constructing the client.
    # Hence, the client library will look for credentials using ADC.
    storage_client = storage.Client(project=project_id)
    buckets = storage_client.list_buckets()
    print("Buckets:")
    for bucket in buckets:
        print(bucket.name)
    print("Listed all storage buckets.")

后续步骤