2013-03-06 50 views
5

我正在使用google-api-php-client 0.6.1,我想知道是否有一種方法可以模擬具有服務帳戶的具體用戶?我的應用程序需要在其谷歌驅動器中存儲一些文件。所以,我已決定使用用戶服務帳戶和.p12密鑰 - 認證。它工作的很好,但所有文件都存儲在服務帳戶中,所以我無法管理它們。我希望將文檔存儲在特定帳戶(用於創建api項目和服務帳戶本身)。我試圖用這個代碼:使用服務帳戶模擬Google用戶

$KEY_FILE = <p12 key file path>; 
$key = file_get_contents($KEY_FILE); 
$auth = new Google_AssertionCredentials(
     $SERVICE_ACCOUNT_NAME, 
     array('https://www.googleapis.com/auth/drive'), 
     $key); 
$auth->prn = '<[email protected]>'; 
$client = new Google_Client(); 
$client->setUseObjects(true); 
$client->setAssertionCredentials($auth); 
return new Google_DriveService($client); 

但我得到了 「錯誤刷新的OAuth2令牌,消息: '{ 」錯誤「: 」ACCESS_DENIED「}'」

+0

我遇到同樣的問題,似乎我應該在谷歌配置本身進行一些更改。你有沒有找到解決方案?你能指出我應該改變什麼嗎? – Sergei 2014-09-22 16:28:10

回答

1

不要用戶$ auth- > prn,使用$ auth-> sub。這適用於我:

// Create a new google client. We need this for all API access. 
$client = new Google_Client(); 
$client->setApplicationName("Google Group Test"); 

$client_id = '...'; 
$service_account_name = '...'; 
$key_file_location = '...'; 

if (isset($_SESSION['service_token'])) { 
    $client->setAccessToken($_SESSION['service_token']); 
} 
$key = file_get_contents($key_file_location); 

// https://www.googleapis.com/auth/admin.directory.group, 
// https://www.googleapis.com/auth/admin.directory.group.readonly, 
// https://www.googleapis.com/auth/admin.directory.group.member, 
// https://www.googleapis.com/auth/admin.directory.group.member.readonly, 
// https://www.googleapis.com/auth/apps.groups.settings, 
// https://www.googleapis.com/auth/books 
$cred = new Google_Auth_AssertionCredentials(
    $service_account_name, 
     array(
      Google_Service_Groupssettings::APPS_GROUPS_SETTINGS, 
      Google_Service_Directory::ADMIN_DIRECTORY_GROUP, 
      Google_Service_Directory::ADMIN_DIRECTORY_GROUP_READONLY, 

      Google_Service_Directory::ADMIN_DIRECTORY_GROUP_MEMBER, 
      Google_Service_Directory::ADMIN_DIRECTORY_GROUP_MEMBER_READONLY, 

      Google_Service_Books::BOOKS, 
     ), 
     $key, 
     'notasecret' 
    ); 
// 
// Very important step: the service account must also declare the 
// identity (via email address) of a user with admin priviledges that 
// it would like to masquerade as. 
// 
// See: http://stackoverflow.com/questions/22772725/trouble-making-authenticated-calls-to-google-api-via-oauth 
// 
$cred->sub = '...'; 
$client->setAssertionCredentials($cred); 
if ($client->getAuth()->isAccessTokenExpired()) { 
    $client->getAuth()->refreshTokenWithAssertion($cred); 
} 
$_SESSION['service_token'] = $client->getAccessToken();