【问题标题】:Google Api Service Account AuthorizationGoogle Api 服务帐号授权
【发布时间】:2017-05-15 09:27:05
【问题描述】:

这是我的 service.php 文件:

putenv('GOOGLE_APPLICATION_CREDENTIALS=service-account.json');
$client = new Google_Client();
$client->useApplicationDefaultCredentials();

$client->setSubject('user@mydomain.com');

$client->setScopes('https://www.googleapis.com/auth/drive.file');

$service = new Google_Service_Drive($client);
//Create a new drive file
$file = new Google_Service_Drive_DriveFile();

$file->setName('example');
$file->setMimeType('application/vnd.google-apps.file');
$data = file_get_contents('exapmle.txt');
  //Upload the file to google docs
$createdFile = $service->files->create($file, array(
        'data' => $data,
        'mimeType' => $mimeType,
        'uploadType' => 'multipart'
      ));

我在同一个工作目录中有 service-account.json 文件。

但我收到此错误:

PHP Fatal error:  Uncaught Google_Service_Exception: {
 "error": "unauthorized_client",
 "error_description": "Client is unauthorized to retrieve access tokens using this method."
}
 in \vendor\google\apiclient\src\Google\Http\REST.php:118

我还启用了 G Suite 域范围委派。

【问题讨论】:

  • 当账户配置不正确时会发生这种错误......也许this issue可以帮助你找出你错过了什么。
  • 确保您已设置域委托developers.google.com/identity/protocols/… 您的服务帐户需要访问 user@mydomain.com 文件。
  • 嗨@DaImTo,我已经设置了域委托。我在问题的最后一行也提到了。
  • 嗨@ElmerDantas,我已经使用链接[link](developers.google.com/identity/protocols/…)配置了帐户,我可以成功阅读用户的电子邮件,但无法上传文件。
  • 我发现您的代码存在三个问题: - 授权错误表明未配置 DwD,或者您使用了错误的范围。代码中的范围必须与安全 > 高级 > 管理 API 客户端访问下的范围完全相同。 - 您的代码在元数据数组中使用了未定义的 $mimeType 变量。如果要在数组中使用 $mimeType 变量,请确保预先定义好它。 - 文件名似乎拼写错误,“exapmle.txt”而不是“example.txt”。确保文件的路径正确,并且指定的文件确实存在。

标签: php google-api google-api-php-client


【解决方案1】:

把我的笔记放在完整的上下文中:

在代码中定义了 Drive.file 范围:

$client->setScopes('https://www.googleapis.com/auth/drive.file');

但在 Security > Advanced > Manage API client access 下的管理控制台中,范围列表授权以下内容进行域范围的委派。

https://googleapis.com/auth/drive

https://developers.google.com/identity/protocols/OAuth2ServiceAccount#delegatingauthority所示,

  1. 在一个或多个 API 范围字段中,输入应授予您的应用程序访问权限的范围列表。例如,如果您的应用程序需要在域范围内访问 Google Drive API 和 Google Calendar API,请输入:https://www.googleapis.com/auth/drivehttps://www.googleapis.com/auth/calendar

由于请求的范围与为客户端 ID 授权的范围列表中的范围不匹配,因此授权被拒绝,并出现 403 错误。

【讨论】:

    猜你喜欢
    • 2017-06-13
    • 1970-01-01
    • 1970-01-01
    • 2013-08-21
    • 1970-01-01
    • 2012-11-24
    • 1970-01-01
    • 2020-01-06
    • 2020-02-22
    相关资源
    最近更新 更多