繁体   English   中英

Google Drive API不允许未经PHP身份验证上传文件

[英]Google drive API is not allowing to upload files without authentication with PHP

我正在使用该库和Google php客户端库,并遵循Google Drive快速入门教程。

$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云端硬盘。 当我运行要上传的应用程序时,它正在请求授权。 为此,要求我登录我的Google帐户并同意访问我的驱动器帐户,然后再返回我的应用程序。

我想跳过这一步。 我如何上传到Google云端硬盘而不需要获得Google的授权。

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

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

如果您要访问的帐户是您自己的帐户,开发人员可以控制该帐户,那么您可以使用服务帐户。 服务帐户用于服务器到服务器的身份验证。 服务帐户已预先授权。 您将要做的就是获取服务帐户的电子邮件地址,并在您的Google Drive帐户上共享一个您希望它可以访问的目录或文件。 一旦您授予它访问权,便可以访问它,而无需登录。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM