【问题标题】:google drive API authorize issue谷歌驱动API授权问题
【发布时间】:2014-02-18 17:38:05
【问题描述】:

我按照谷歌驱动器上的教程进行操作,它说要保留身份验证/访问令牌,我们必须使用刷新令牌,这样我们就不必在每次进行 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 调用而无需再次向用户请求授权??

有什么想法吗??

谢谢,
阿尼克特

【问题讨论】:

    标签: php google-drive-api


    【解决方案1】:

    可能,最好使用 P12 密钥使用服务器到服务器身份验证: 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 云端硬盘中列出的所有文件,而无需任何客户端用户交互。

    【讨论】:

    • 我遇到了Google_Auth_AssertionCredentials 的问题,但找到了文件并将函数更改为Google_AssertionCredentials。但现在我有问题:PHP Fatal error: Cannot call constructor in google_drive\vendor\google\apiclient-services\src\Google\Service\Drive.php on line 75
    猜你喜欢
    • 2012-12-24
    • 1970-01-01
    • 1970-01-01
    • 2012-12-15
    • 1970-01-01
    • 2014-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多