首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Google drive API不允许在未经PHP验证的情况下上传文件

问Google drive API不允许在未经PHP验证的情况下上传文件
EN

Stack Overflow用户
提问于 2018-09-03 02:51:00
回答 1查看 1.1K关注 0票数 0

我正在使用这个库,Google php客户端库,并遵循google drive quickstart教程。

代码语言:javascript
复制
$client = new Google_Client();
$client->setApplicationName('Google Drive API PHP Quickstart');
$client->setScopes(Google_Service_Drive::DRIVE_METADATA_READONLY);
$client->setAuthConfig('credentials.json');
$client->setAccessType('offline');

我正在尝试将我的文件从PHP应用程序上传到Google Drive。当我运行要上传的应用程序时,它要求授权。要做到这一点,它要求我登录到我的google帐户,并同意访问我的驱动器帐户,然后才能返回我的应用程序。

我想跳过这一步。如何上传到Google drive,而不需要向google授权。

EN

回答 1

Stack Overflow用户

发布于 2018-09-04 01:00:17

您首先需要了解的是私有数据和公共数据之间的区别。私有数据归用户所有,而公共数据是公共数据,任何人都可以访问它。

谷歌硬盘的数据是私人用户数据。为了访问它,您必须拥有拥有它的用户的权限。获得该权限的最常见方法是使用Oauth2并弹出您在现在的代码中看到的同意屏幕。不过,还有另一种选择。

如果您正在访问的帐户是您自己的帐户,并且您作为开发人员可以控制该帐户,那么您可以使用服务帐户。服务帐户用于服务器到服务器的身份验证。服务帐户是预先授权的。您要做的是获取服务帐户的电子邮件地址,并在您的google驱动器帐户上共享您希望其有权访问的目录或文件。一旦您授予它访问权限,它将拥有访问权限,无需登录。

代码语言:javascript
复制
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();
    }
}

我在服务帐户上的示例。serviceaccount.php

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52140113

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档