谷歌云端硬盘API不允许在没有PHP身份验证的情况下上传文件



我正在使用这个库谷歌 php 客户端库,并按照谷歌驱动器快速入门教程进行操作。

$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 云端硬盘数据是私密用户数据。 为了访问它,您必须拥有拥有它的用户的权限。 获得该权限的最常见方法是使用 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();
}
}

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

相关内容

最新更新