从本地主机获取 Google 凭据(不指定 serviceAccount/privateKey)

Get GoogleCredentials from localhost (without specifiying serviceAccount/privateKey)

我既在本地,也在我们的 Kubernetes pods 中,通过 Google 云的身份验证。在两者上,我都可以通过 gcloud info.

得到正确的响应

但是,当我想访问GoogleDrive时,我需要使用GoogleCredential,如下所示:

        GoogleCredential.Builder()
                .setTransport(transport)
                .setJsonFactory(jsonFactory)
                .setServiceAccountPrivateKey(privateKey)
                .setServiceAccountId(serviceAccount)
                .setServiceAccountScopes(scopes.toList()).build()

意思-我需要专门设置privateKey和serviceAccount。有没有办法强制它使用本地认证的帐户?

当使用 Google 个桶时,这可以很容易地完成:

StorageOptions.getDefaultInstance().service.options.credentials

我找不到 Google 驱动器的相同方法。

正如@DazWilkin 指出的那样,许多 GCP 客户端库(例如您的 GCS)知道如何自动检测 "Application Default Credentials" 可用。

这些 ADC 凭据目前仅适用于 Google Cloud Platform APIs(Google Drive 早于此)。您可以阅读 Google Drive Java 快速入门以了解如何检索凭据:https://developers.google.com/drive/api/v3/quickstart/java

作为参考,GCP 客户端库将通过以下方式查找 ADC:

  1. GOOGLE_APPLICATION_CREDENTIALS 环境变量,如果设置,指向服务帐户的 JSON 密钥文件。
  2. 如果用户执行了gcloud auth application-default login命令,则查找%APPDATA%/gcloud/application_default_credentials.json(Windows)或$HOME/.config/gcloud/application_default_credentials.json(其他)。
  3. 在 Google App Engine 第一代(不是 GAE Flex)上使用 appengine.AccessToken API.
  4. 在 GCE、GKE 或 GAE 第二代环境中,它调用 GCE Metadata API (an url like http://metadata.google.internal or http://169.254.169.254) 来检索短暂的 access_token.

在您的情况下,您的 GKE pods 正在使用方法 #4 检索用于 GCS 存储桶操作的令牌;但不适用于云端硬盘 API.