com.google.cloud.datastore.datastoreException:缺少请求所需的身份验证凭证



我正在使用Google App Engine和Google Datastore。我正在使用Google Library

com.google.cloud.datastore.Datastore

我的示例代码是:

Datastore datastore = DatastoreOptions.getDefaultInstance().getService();
Key taskKey = datastore.newKeyFactory().setKind(entityName).newKey(id);
//populate some fields....
datastore.put(task);

我正在使用弹簧靴和码头作为容器。

在本地,它正在正常工作,并且在Google数据存储中更新了数据。

问题是当我将应用程序部署到Google-App-engine时,我在到达dataStore.put方法时得到以下例外。

com.google.cloud.datastore.DatastoreException: Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential. See https://developers.google.com/identity/sign-in/web/devconsole-project.
com.google.cloud.datastore.spi.v1.HttpDatastoreRpc.translate(HttpDatastoreRpc.java:129)
com.google.cloud.datastore.spi.v1.HttpDatastoreRpc.commit(HttpDatastoreRpc.java:155)
com.google.cloud.datastore.DatastoreImpl$4.call(DatastoreImpl.java:485)

注意:在本地环境和Google-app-engine上,我定义了环境变量Google_application_credentials,该变量指向JSON文件,并具有Google API生成的所有必需凭据。

根据用于从Java的App Engine连接到数据存储的文档,有几个选项可用,因此您可以使用 Objectify (第三方库(使用,数据存储API datastore客户端库

使用客户端库的使用,您必须知道它们使用应用程序默认凭据,以至于如有记录的方式,如果环境变量GOOGLE_APPLICATION_CREDENTIALS,ADC使用应用程序引擎为应用程序提供的默认服务帐户运行该服务。因此,就您而言,我认为您不应该定义环境变量,以便App Engine使用其默认服务帐户。

如果您仍在使用com.google.cloud.datastore.DatastoreException: Request is missing required authentication credential. Expected OAuth 2 access token, login cookie or other valid authentication credential.挣扎,则可以明确设置凭据,如下所示:

            Resource credentialsCyberpower = resourceLoader.getResource("classpath:yourservice-datastore-access.json");

            GoogleCredentials credentials = GoogleCredentials.fromStream(credentialsCyberpower.getInputStream())
                  .createScoped(Lists.newArrayList("https://www.googleapis.com/auth/cloud-platform"));
            DatastoreOptions options =
                    DatastoreOptions.newBuilder().setProjectId("XXXXXX").setCredentials(credentials).build();
            Datastore datastore = options.getService();
            ObjectifyService.init(new ObjectifyFactory(datastore));

在IAM服务帐户中生成yourservice-datastore-access.json。与Abtocerify 6.0.5

一起工作

如果您使用java8的 <url-stream-handler>urlfetch</url-stream-handler>并客观化6,则必须切换到 native并启用计费。

我最近被这个问题击中,花了很多时间来解决问题,可以在此处找到更多信息

最新更新