如何使用服务帐户搜索文件/在另一个用户文件夹中打开/创建Google表格?

问题描述:

这是场景。我有一个帐户,用于保存测试结果电子表格。我有一个服务帐户,用于编程(使用java和谷歌驱动器apiv3)来添加/更新这些电子表格。我需要一种方法来创建电子表格并从服务帐户中搜索用户帐户和文件夹中的电子表格。我有以下代码获取文件列表,但它是服务帐户文件夹中的文件,而不是用户帐户文件夹。任何帮助?如何使用服务帐户搜索文件/在另一个用户文件夹中打开/创建Google表格?

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; 
} 

似乎没有办法使用API​​在Google云端硬盘中执行我想要的操作。我最终做的是创建表单作为“服务帐户”,然后将所有权转让给我想要的用户,然后将其分享给需要访问的组。这很好用!

从这个documentation基础,域管理员可以使用服务帐户使用OAuth 2.0下放权力这样。

在企业应用程序中,您可能希望以编程方式访问用户数据,而无需任何人工授权。在G Suite域中,域管理员可以授予第三方应用程序对其用户数据的域范围访问权 - 这被称为域范围授权。

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

有关更多信息,您可能会看到Using OAuth 2.0 for Server to Server Applications文档。

+0

我们不使用GSuite域名。我也不是域管理员。不幸的是,这是行不通的。 – GregMa