有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

javacom。谷歌。云数据存储。DatastoreException:请求缺少必需的身份验证凭据

我正在使用谷歌应用程序引擎和谷歌数据存储。 我正在使用谷歌图书馆

com.google.cloud.datastore.Datastore

我的示例代码是:

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

我使用spring boot和jetty作为容器

在本地,它工作正常,数据在google数据存储中更新

问题是,当我将应用程序部署到google应用程序引擎时,当我访问数据存储时,我会得到以下异常。放方法

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)

注意:在local environment和google app engine上,我都定义了环境变量google_APPLICATION_CREDENTIALS,该变量指向json文件,其中包含由google API生成的所有必需凭据


共 (3) 个答案

  1. # 1 楼答案

    根据connecting to Datastore from App Engine in Java的文档,有几个选项可用,因此您可以使用Objectify(第三方库)、数据存储API数据存储客户端库

    在使用客户端库时,您必须知道它们使用了Application Default Credentials,正如文件所述,如果环境变量GOOGLE_APPLICATION_CREDENTIALS,ADC将使用App Engine为通过该服务运行的应用程序提供的默认服务帐户。因此,在您的情况下,我认为您不应该定义环境变量,以便App Engine使用其默认服务帐户

  2. # 2 楼答案

    如果在Java8和Objectify 6中使用<url-stream-handler>urlfetch</url-stream-handler>,则必须切换到native并启用计费

    我最近遇到了这个问题,花了很多时间来解决这个问题,更多信息可以找到here

  3. # 3 楼答案

    如果仍在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。使用Objectify 6.0.5