代码之家  ›  专栏  ›  技术社区  ›  Petr Kozelka

如何模拟在G-Suite域中运行的AppEngine java应用程序的用户?

  •  10
  • Petr Kozelka  · 技术社区  · 7 年前

    我的标准AppEngine应用程序需要在Google工作表文档(以及其他文档)中执行更改。

    为了实现这一点,我需要获取服务帐户的凭据,并以某种方式配置它应该代表用户进行操作。

    此方法允许为我提供默认服务帐户凭据:

    private static GoogleCredential getDefaultServiceAccountCredential() throws IOException {
        return GoogleCredential.getApplicationDefault()
            .createScoped(MY_SCOPES);
    }
    

    但它并不代表用户。

    以下代码类似,使用其他(非默认)服务帐户,但仍不会发生模拟:

    private static GoogleCredential getNonDefaultServiceAccountCredential() throws IOException {
        return GoogleCredential.fromStream(IncomingMailHandlerServlet.class.getResourceAsStream("/tokens/anoher-e6351a8c5b91.json"))
            .createScoped(MY_SCOPES);
    }
    

    对于模拟, Google Docs (还有许多建议)提到了如何使用PKCS12文件;但是,该文件只能读取为 PrivateKey 在已安装的应用程序上,而不是在AppEngine上。

    有没有办法为在AppEngine中运行的java应用程序获取模拟凭据? 或者,从 File 在AppEngine上?

    请注意,对于我尝试的所有服务帐户,我都使用角色所有者和DwD(域范围委派)对它们进行了配置。是否还有其他配置?

    1 回复  |  直到 7 年前
        1
  •  5
  •   Tudormi    7 年前

    这个 GoogleCredential reference 向提供示例

    还可以使用服务帐户流模拟您拥有的域中的用户。这与上面的服务帐户流非常相似,但您需要另外调用 GoogleCredential.Builder.setServiceAccountUser(String)

     public static GoogleCredential createCredentialForServiceAccountImpersonateUser(
          HttpTransport transport,
          JsonFactory jsonFactory,
          String serviceAccountId,
          Collection<String> serviceAccountScopes,
          File p12File,
          String serviceAccountUser) throws GeneralSecurityException, IOException {
        return new GoogleCredential.Builder().setTransport(transport)
            .setJsonFactory(jsonFactory)
            .setServiceAccountId(serviceAccountId)
            .setServiceAccountScopes(serviceAccountScopes)
            .setServiceAccountPrivateKeyFromP12File(p12File)
            .setServiceAccountUser(serviceAccountUser)
            .build();
      }
    

    关于如何从App Engine Standard访问文件,有多个选项。下面介绍了两个选项:


    选项1: p12File (凭据文件)是 App Engine Standard resource file . 检查 this answer 要查看如何访问此类文件,请按代码进行。我强烈推荐这种方法,因为

    这些文件仅在只读基础上对您的代码可用,不用于流量服务。

    File f = new File("path/below/my/project/directory/credentials.json");
    

    以及 appengine-web.xml 应定义资源文件:

    <resource-files>
      <include path="path/below/my/project/directory/credentials.json"/>
    </resource-files>
    


    选项2:凭据文件位于云存储中。这 document 解释如何从App Engine Standard访问云存储中的文件。但我认为这太麻烦了。我也提供了这个选项,因为我已经提到了它。