无法将文件的所有权从服务帐户转移到google驱动器用户



当试图转移所有权时,我收到以下错误:

"domain": "global",
"reason": "invalidSharingRequest",
"message": "Bad Request. User message: "You can't change the owner of this item.""

这是我的代码:

use Google_Client; 
use Google_Service_Drive;
use Google_Service_Drive_DriveFile;
use Google_Service_Drive_Permission;
public function uploadDocument() {
$FOLDER_ID = 'my_folder_ID_string';
$client = new Google_Client();
$client->setAuthConfig(base_path('service_account_credentials.json'));
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$service = new Google_Service_Drive($client);
$fileMetadata = new Google_Service_Drive_DriveFile(array(
'name' => 'Test.pdf',
'parents' => [$FOLDER_ID]
));
$content = file_get_contents(public_path('tmp/Test.pdf'));
$file = $service->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => 'application/pdf',
'uploadType' => 'multipart',
'fields' => 'id'
));
// Transfer Ownership
$newPermission = new Google_Service_Drive_Permission();
$newPermission->setRole('owner');
$newPermission->setType('user');
$newPermission->setEmailAddress('email@gmail.com');
$optParams = array('transferOwnership' => 'true');
$service->permissions->create($file->id, $newPermission, $optParams);
}

文件夹已成功上传到共享文件夹中的Google Drive(所有者为email@gmail.com',服务帐户是'editor'(,但是上载文件的所有者是服务帐户,编辑器是'email@gmail.com"。

您不能更改位于共享驱动器上的文件的所有者

根据文件:

共享驱动器中的文件归共享驱动器所有,而非个人用户所有。

因此,没有必要";拿走";服务帐户的所有权。

您可以赋予用户任何其他角色,例如organizer,这将允许用户将文件移出共享驱动器,从而成为文件的所有者。\

更新

如果服务帐户将文件上载到用户驱动器上的共享文件夹,而不是共享驱动器,则情况会有所不同。

具体而言:

  • 对于GSuite用户,不允许在域外转移所有权,这将导致错误CCD_ 2
  • 服务帐户不被视为域用户,因此受到相同的限制
  • 对于消费者用户,允许但限制将所有权从服务帐户转移到用户:只有Google mimeType的文档才能更改所有者
  • 由于上述将所有权从服务帐户转移到用户的限制,最好通过使用模拟来避免此问题
  • 模拟意味着服务帐户代表用户(例如您(,当他将文件上传到您的驱动器时,这相当于您自己上传文件时-不需要转移所有权,也不需要与服务帐户明确共享文件夹
  • 要设置模拟,您需要
    • 在GCP控制台中为特定服务帐户启用域范围的delation。

    • 通过转到Security > API Controls > Domain wide delegation,在管理控制台中授权服务帐户所需的所有作用域。

    • 通过添加行修改代码

      $client->setSubject($EmailOfUserToImpersonate);

  • 请注意,不幸的是,域范围的委派仅适用于域,即GSuite帐户
  • 对于消费者(gmail(帐户,不可能将非Google mimeType的所有权从服务帐户转移到用户
  • 作为一种变通方法,用户可以复制服务帐户上传的文件,随后服务帐户可以删除原始文件

最新更新