谷歌驱动器API授权问题

时间:2014-02-18 17:38:05

标签: php google-drive-api

我按照google驱动器上的教程,它说要保持身份验证/访问令牌,我们必须使用刷新令牌,这样我们就不必在每次进行API调用时都要求用户进行身份验证/授权

代码:

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调用而无需再次询问用户的授权??

有什么想法吗?

谢谢,
Aniket

1 个答案:

答案 0 :(得分:0)

使用P12密钥最好使用Server to Server身份验证: https://developers.google.com/api-client-library/php/auth/service-accounts

您可以模拟用户帐户,服务器可以访问所有文件。

$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云端硬盘中列出的所有文件,而无需任何客户端用户互动。