【问题标题】:Use Google Drive API "without" authentication screen from php使用来自 php 的“无”身份验证屏幕的 Google Drive API
【发布时间】:2020-05-03 12:12:57
【问题描述】:

这就是我面临的情况。 我有一个 php 支持的 Web 应用程序,我需要从中访问我的 Google Drive 帐户中的一些文件链接。我只需要访问我帐户中的文件,因为我存储了相同的图像,我必须为不同的客户提供服务。 我试图查看 Google Drive API 文档,但我不需要 OAuth 和同意屏幕。该应用应该在“后台”访问我的 Google Drive 帐户,只是为了检索它必须呈现给客户的一些信息,而无需他们做任何事情。

我在 StackOverflow 上阅读了非常相似的问题,但这些问题都没有真正帮助我……有些人提到了服务帐户的使用,另一些人说它们对此没有用处。

您能否帮助我了解在这种情况下哪种方法最好?提前非常感谢!

【问题讨论】:

标签: php google-drive-api google-oauth google-api-php-client service-accounts


【解决方案1】:

您正在寻找的是一个服务帐户。服务帐户是虚拟用户,他们实际上拥有自己的 Google Drive 帐户。由于他们是用户,因此您可以像与任何其他用户一样与他们共享文件。一旦文件与服务帐户共享,它就可以访问它,然后可以像使用 Oauth2 一样在您登录时使用它,您不需要登录并同意访问,因为您已经配置了访问权限。

require_once __DIR__ . '/vendor/autoload.php';

// Use the developers console and download your service account
// credentials in JSON format. Place the file in this directory or
// change the key file location if necessary.
putenv('GOOGLE_APPLICATION_CREDENTIALS='.__DIR__.'/service-account.json');

/**
 * Gets the Google client refreshing auth if needed.
 * Documentation: https://developers.google.com/identity/protocols/OAuth2ServiceAccount
 * Initializes a client object.
 * @return A google client object.
 */
function getGoogleClient() {
    return getServiceAccountClient();
}

/**
 * Builds the Google client object.
 * Documentation: https://developers.google.com/api-client-library/php/auth/service-accounts
 * Scopes will need to be changed depending upon the API's being accessed. 
 * array(Google_Service_Analytics::ANALYTICS_READONLY, Google_Service_Analytics::ANALYTICS)
 * List of Google Scopes: https://developers.google.com/identity/protocols/googlescopes
 * @return A google client object.
 */
function getServiceAccountClient() {
    try {   
        // Create and configure a new client object.        
        $client = new Google_Client();
        $client->useApplicationDefaultCredentials();
        $client->addScope([YOUR SCOPES HERE]);
        return $client;
    } catch (Exception $e) {
        print "An error occurred: " . $e->getMessage();
    }
}

【讨论】:

  • 如果使用服务帐户,我建议在这里使用domain-wide delegation,这样您就可以冒充自己并直接获取文件,而不必与它共享每个文件。
  • 非常感谢你们俩!我设法使用服务帐户通过客户端 PHP 库访问我的云端硬盘,现在我面临另一个问题...如何列出或读取从我的帐户与服务帐户共享的文件的某些属性?例如,我可以通过服务帐户将文件上传到共享目录,但我无法从服务帐户访问共享文件。你能帮我吗?
  • @davideferrè 作为另一个问题提出。如果服务帐户的上传文件确保您更改权限以授予自己访问权限,则服务帐户可能会很棘手。也尝试做一个 file.list 添加 q 参数并寻找与我共享。 developers.google.com/drive/api/v2/ref-search-terms
  • 谢谢,我已经知道如何解决这个问题了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多