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

问题描述 投票:0回答:1

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

$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驱动器。

php google-api google-drive-api google-api-php-client
1个回答
0
投票

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

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

如果您正在访问的帐户是您自己的帐户,那么您可以使用服务帐户。服务帐户用于服务器到服务器身份验证。服务帐户是预先授权的。您要做的是获取服务帐户的电子邮件地址,并共享您希望其有权访问的Google云端硬盘帐户中的目录或文件。一旦您授予其访问权限,它将具有访问权限,无需登录。

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

© www.soinside.com 2019 - 2024. All rights reserved.