身份验证谷歌云 API



我正在尝试使用 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时,我看到我已使用在我的项目中授予所有者的凭据登录。为什么我会收到此错误?

即使您通过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();

最新更新