谷歌驱动器API授权问题 [英] google drive API authorize issue
问题描述
我跟着谷歌驱动器上的教程,它说要持久化身份验证/访问令牌,我们必须使用刷新令牌,这样我们就不必要求用户在每次进行API调用时进行身份验证/授权。
I followed the tutorial on the google drive, it says that to persist the authentication/access token we have to use refresh token, so that we don't have to ask user to authenticate/authorize every time we make an API call.
代码:
Code:
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_DriveService.php';
$client = new Google_Client();
// Get your credentials from the console
$client->setClientId('client ID');
$client->setClientSecret('client secret');
$client->setRedirectUri('URL');
$client->setScopes(array('https://www.googleapis.com/auth/drive'));
$client->setAccessType('offline');
$service = new Google_DriveService($client);
$authUrl = $client->createAuthUrl();
// Exchange authorization code for access token
$accessToken = $client->authenticate();
$client->setAccessToken($accessToken);
$files = $service->files->listFiles();
echo "<pre>"; print_r($files);
这给我一个文件和文件夹列表,但每次刷新页面时,到谷歌授权页面。我可以将访问令牌保存在数据库中,但是如何使用它并进行API调用,而不再需要用户授权?
This gives me the list of files and folders, but every time I refresh the page it takes me back to google authorization page. I can save the access token in database but how to use that and make API calls without again asking authorization from the user??
任何想法??
感谢,
Aniket
Thanks,
Aniket
推荐答案
通过使用P12键使用服务器到服务器身份验证:
https://developers.google.com/api-client-library/php/auth/service-accounts
Probably, it's better to use Server to Server authentication by using P12 key: https://developers.google.com/api-client-library/php/auth/service-accounts
您可以模拟一个用户帐户和所有文件将被您的服务器访问。
You can impersonate a user account and all files will be accessible by your server.
$client_email = '1234567890- a1b2c3d4e5f6g7h8i@developer.gserviceaccount.com';
$private_key = file_get_contents('MyProject.p12');
$user_to_impersonate = 'user@example.org';
$private_key = file_get_contents($pkey); //notasecret
$scopes = array('https://www.googleapis.com/auth/drive');
$credentials = new \Google_Auth_AssertionCredentials(
$client_email,
$scopes,
$private_key,
'notasecret', // Default P12 password
'http://oauth.net/grant_type/jwt/1.0/bearer', // Default grant type
$user_to_impersonate
);
$client = new \Google_Client();
$client->setAssertionCredentials($credentials);
if ($client->getAuth()->isAccessTokenExpired()) {
$client->getAuth()->refreshTokenWithAssertion();
}
$service = new \Google_Service_Drive($client);
$files = $service->files->listFiles();
echo "count files=".count($files)."<br>";
foreach( $files as $item ) {
echo "title=".$item['title']."<br>";
}
这将为您提供Google云端硬盘中列出的所有文件,而无需任何客户端用户互动。
This will give you all files listed in your Google Drive without any client user interaction.
这篇关于谷歌驱动器API授权问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!