【问题标题】:Authentication Google Cloud APIs身份验证 Google Cloud API
【发布时间】:2018-07-26 14:50:36
【问题描述】:
我正在尝试使用 BigQuery 客户端并遇到身份验证错误:
<groupId>com.google.apis</groupId>
<artifactId>google-api-services-bigquery</artifactId>
<version>v2-rev397-1.23.0</version>
com.google.api.client.googleapis.json.GoogleJsonResponseException: 401
未经授权
我在路径中没有服务帐户,因为我是该项目的所有者,并且通过 gcloud auth login 登录到我的帐户。当我尝试gcloud auth list 时,我看到我使用在我的项目中授予所有者的凭据登录。为什么会出现此错误?
【问题讨论】:
标签:
google-cloud-platform
google-authentication
【解决方案1】:
即使您通过 gcloud auth login 登录,也不意味着您的应用程序将使用这些凭据。您仍然需要使用 OAuth 2.0 进行身份验证。
如果您希望使用您的用户帐户进行身份验证,可以尝试生成访问令牌并将其传递给 GoogleCredential 类(请注意令牌过期)。
要为您的用户凭据生成访问令牌,请使用 gcloud 工具:
gcloud auth application-default print-access-token
将生成的令牌传递给 GoogleCredential 类:
GoogleCredential credential = new GoogleCredential().setAccessToken(accessToken);
我对 google-api-services-bigquery API 不是很熟悉,但我认为这是您使用凭证的方式:
Bigquery bigquery = Bigquery.builder(HTTP_TRANSPORT, JSON_FACTORY).setHttpRequestInitializer(credential).build();