我正在Google App Engine上运行服务,我想从Cloud Storage Bucket读取一些文件。

正如我在此处阅读的https://cloud.google.com/docs/authentication/production#obtaining_credentials_on_app_engine_standard_environment一样,您可以隐式或显式获取凭据。

我在运行时java8上运行服务。

在我的服务中,我尝试了两种方法,但它们都不起作用。

隐式方式

StorageOptions.getDefaultInstance().getService();


当我使用隐式方式时,我总是会收到此错误

com.google.cloud.storage.StorageException: Anonymous caller does not have storage.buckets.get access to xxxxxxxxxx.
at com.google.cloud.storage.spi.v1.HttpStorageRpc.translate(HttpStorageRpc.java:229)
at com.google.cloud.storage.spi.v1.HttpStorageRpc.get(HttpStorageRpc.java:406)
at com.google.cloud.storage.StorageImpl$4.call(StorageImpl.java:215)
at com.google.cloud.storage.StorageImpl$4.call(StorageImpl.java:212)
at com.google.api.gax.retrying.DirectRetryingExecutor.submit(DirectRetryingExecutor.java:105)
at com.google.cloud.RetryHelper.run(RetryHelper.java:76)


显式方式

GoogleCredentials credentials = AppEngineCredentials.getApplicationDefault();
storage = StorageOptions.newBuilder().setCredentials(credentials).build().getService();


通过为AppEngine应用显式方式,我收到此错误

The Application Default Credentials are not available. They are available if running in Google Compute Engine. Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials. See https://developers.google.com/accounts/docs/application-default-credentials for more information.


我正在使用依赖

    <dependency>
        <groupId>com.google.cloud</groupId>
        <artifactId>google-cloud-storage</artifactId>
        <version>1.92.0</version>
    </dependency>


在本地环境上运行的作品。

提前致谢

最佳答案

在运行时Java8上唯一适用于我的代码是这样的

import com.google.appengine.api.appidentity.AppIdentityService;
import com.google.appengine.api.appidentity.AppIdentityServiceFactory;
import com.google.auth.appengine.AppEngineCredentials;
import com.google.auth.oauth2.GoogleCredentials;
import com.google.cloud.storage.*;

AppIdentityService appIdentityService = AppIdentityServiceFactory.getAppIdentityService();
GoogleCredentials credentials = AppEngineCredentials.newBuilder().setAppIdentityService(appIdentityService).build();
storage = StorageOptions.newBuilder().setCredentials(credentials).build().getService();

10-05 18:53