首页 > 解决方案 > 谷歌服务器到服务器 OAuth2 PHP 示例不起作用

问题描述

我正在按照此示例在我的 PHP 应用程序和 Google Cloud API 之间进行服务器到服务器访问, https://developers.google.com/api-client-library/php/auth/service-accounts。特别是,我需要访问 Drive API。

当我运行应用程序时,虽然我收到以下错误:

   Google_Service_Exception  : {
      "error": "unauthorized_client",
      "error_description": "Client is unauthorized to retrieve access tokens using this method, or client not authorized for any of the scopes requested."
    }

这是我所做的:

我错过了一步吗?

这是我的代码:

    putenv('GOOGLE_APPLICATION_CREDENTIALS=my_storage/secure/my-app-service-account.json');

    $client = new \Google_Client();
    $client->setScopes(\Google_Service_Drive::DRIVE_METADATA_READONLY);
    $client->useApplicationDefaultCredentials();
    $client->setSubject('my_email@my_domain.com');
    $drive = new \Google_Service_Drive($client);

    echo $drive->about->get();

该示例不包括setScopes()调用,但是没有它我得到了与范围相关的错误。(该示例不是基于 Drive API,所以在这种情况下可能不需要它?)

更新:在 GCP 的 IAM 设置中,我将服务帐户的电子邮件地址添加为项目所有者,但这没有任何区别。

标签: phpgoogle-apigoogle-oauthgoogle-api-php-client

解决方案


我发现了问题。

setScopes()上面的调用中,传递的值需要与在 G Suite 中设置客户端时给出的值相同,在本例中为https://www.googleapis.com/auth/drive


推荐阅读