0

我正在尝试使用远程 API 从另一个 GAE 项目访问一个应用程序的 DataStore。我正在使用以下代码:

        String serverString = "http://example.com";//this should be the target appengine
    RemoteApiOptions options;
    if (serverString.equals("localhost")) {
        options = new RemoteApiOptions().server(serverString, 8080).useDevelopmentServerCredential();
    } else {
        options = new RemoteApiOptions().server(serverString, 80).useApplicationDefaultCredential();
    }
    RemoteApiInstaller installer = new RemoteApiInstaller();

    installer.install(options);
    datastore = DatastoreServiceFactory.getDatastoreService();

    try {
        results = datastore.get(KeyFactory.createKey("some key"));
    } catch (EntityNotFoundException e) {
        e.printStackTrace();
        return null;
    }

当我在本地运行它时,我在installer.install(options);. 部署后,从 appengine 上的错误报告中看到的错误是:话虽如此HttpResponseException: 401 You must be logged in as an administrator, or access from an approved application. ,我使用以下代码制作了一个小型 java 应用程序:

String serverString = "http://example.com";//same string as the one used in the above code
    RemoteApiOptions options;
    if (serverString.equals("localhost")) {
        options = new RemoteApiOptions().server(serverString, 8080).useDevelopmentServerCredential();
    } else {
        options = new RemoteApiOptions().server(serverString, 80).useApplicationDefaultCredential();
    }
    RemoteApiInstaller installer = new RemoteApiInstaller();
    installer.install(options);
    try {
        DatastoreService ds = DatastoreServiceFactory.getDatastoreService();
        System.out.println("Key of new entity is " + ds.put(new Entity("Hello Remote API!")));

这个有效!添加了 Hello Remote API 实体。

4

1 回答 1

0

在 App Engine 上运行与在本地运行时它不起作用的原因与正在获取的凭据有关。在本地运行时,可能会使用您自己的凭据(可以访问两个项目);相比之下,在 App Engine 上运行时,您可能会选择 App Engine 默认服务帐户,该帐户只能访问该 App Engine 项目。

尝试通过为包含您希望访问的 Cloud Datastore 的项目打开Cloud Console 的 Cloud IAM 部分来解决此问题。在那里,授予对其他项目正在使用的默认 App Engine 服务帐户的适当访问级别。

如果您不希望其他项目中的所有 App Engine 服务都具有这种访问权限,您也可以考虑为此跨项目访问权限生成一个服务帐户,并授予您适当的访问权限(而不是授予该权限)访问默认 App Engine 服务帐户)。然后,在调用 API 的代码中,您将通过调用useServiceAccountCredential()方法显式使用该服务帐户,RemoteApiOptions以确保发出的 API 请求使用指定的服务帐户而不是默认的 App Engine 服务帐户。

于 2017-05-22T06:55:54.327 回答