【问题标题】:How do I search for a file/open/create a googlesheet in another users folder using a service account?如何使用服务帐户在另一个用户的文件夹中搜索文件/打开/创建谷歌表格?
【发布时间】:2017-09-26 15:33:18
【问题描述】:

这里是场景。我有一个帐户,用于保存测试结果电子表格。我有一个服务帐户,用于以编程方式(使用 java 和 google drive apiv3)来添加/更新这些电子表格。我需要一种方法来创建电子表格并从服务帐户的用户帐户和文件夹中搜索电子表格。我有以下代码获取文件列表,但它是服务帐户文件夹中的文件,而不是用户帐户文件夹。有什么帮助吗?

private static boolean findSpreadsheetFile(String sSpreadsheetName)
                throws GeneralSecurityException, IOException, URISyntaxException
{
    String pageToken = null;
    // Build a new authorized API client service.
    Drive driveService = getDriveService();
    // Print the names and IDs
    do
    {
        FileList result = driveService.files().list()
                        .setPageToken(pageToken)
                        .setFields("nextPageToken, files(id, name)")
                        .execute();
        for (com.google.api.services.drive.model.File file : result.getFiles())
        {
            System.out.printf("Found file: %s (%s)\n", file.getName(), file.getId());
        }
        pageToken = result.getNextPageToken();
    }
    while (pageToken != null);
    return true;
}

public static Drive getDriveService() throws GeneralSecurityException, IOException, URISyntaxException
{
    Credential credential = authorizeDrive();
    return new Drive.Builder(HTTP_TRANSPORT, JSON_FACTORY, credential).setApplicationName(APPLICATION_NAME).build();
}

private static GoogleCredential authorizeDrive() throws GeneralSecurityException, IOException, URISyntaxException
{
    JacksonFactory JSON_FACTORY = JacksonFactory.getDefaultInstance();
    HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
    URL fileUrl = ParseTestResultsEmails.class.getResource(sP12Filename);
    GoogleCredential credential = new GoogleCredential.Builder().setTransport(httpTransport)
                    .setJsonFactory(JSON_FACTORY).setServiceAccountId(sServiceAccountID)
                    .setServiceAccountPrivateKeyFromP12File(new File(fileUrl.toURI()))
                    .setServiceAccountScopes(DRIVE_SCOPES).build();
    return credential;
}

【问题讨论】:

    标签: java selenium google-drive-api google-sheets-api


    【解决方案1】:

    基于此documentation,域管理员可以使用具有 OAuth 2.0 的服务帐户以这种方式委派权限。

    在企业应用程序中,您可能希望在没有任何手动授权的情况下以编程方式访问用户数据。在 G Suite 域中,域管理员可以向第三方应用程序授予域范围内对其用户数据的访问权限——这称为域范围内的授权。

    警告:服务帐户只能用于在有效身份是域中单个用户的身份的情况下执行委派。使用服务帐户作为共同所有者来创建许多共享文档可能会对性能产生严重影响。此外,服务帐号可能不会获得额外的存储配额,也不会充当域成员。

    您可以查看Using OAuth 2.0 for Server to Server Applications 文档了解更多信息。

    【讨论】:

    • 我们不使用 GSuite 域。我也不是域管理员。不幸的是,这行不通。
    【解决方案2】:

    似乎没有办法使用 API 在 Google Drive 中做我想做的事。我最终做的是将工作表创建为“服务帐户”,然后将所有权转移给我想要的用户,然后可以将其共享给需要访问的组。效果很好!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多