[英]Google Cloud API PHP Client Authentication using Service Account
[英]Google Service Account Authentication PHP
我正在嘗試對服務帳戶進行身份驗證,以便我可以將訪問令牌與客戶端JSON_API庫一起使用。
我查看了這些文章:
https://code.google.com/p/google-api-php-client/source/browse/trunk/examples/prediction/serviceAccount.php
https://code.google.com/p/google-api-php-client/wiki/UsingTheLibrary
https://developers.google.com/storage/docs/authentication#service_accounts https://developers.google.com/accounts/docs/OAuth2#scenarios
這是我的PHP代碼
<?php
require_once 'google-api-php-client/src/Google_Client.php';
const CLIENT_ID = "";
const SERVICE_ACCOUNT_NAME = "";
const KEY_FILE = "super secret path of course ;)";
$client = new Google_Client();
// Loads the key into PKCS 12 format
$key = file_get_contents(KEY_FILE);
$client->setAssertionCredentials(new Google_AssertionCredentials(
SERVICE_ACCOUNT_NAME,
array('https://www.googleapis.com/auth/prediction'),
$key
)
);
$client->setClientId(CLIENT_ID);
$auth = $client->authenticate();
print $auth ? "Returned true" : "Returned false";
print "<br>";
print is_null($client->getAccessToken()) ? "It's null" : "Works";
?>
這是我的輸出:
歸還是真的
它是空的
我終於想出了在使用不同資源的混合之后如何使用PHP API庫進行身份驗證。
這是我的google php api libray的身份驗證類
<?php
require_once 'google-api-php-client/src/Google_Client.php';
require_once 'google-api-php-client/src/contrib/Google_StorageService.php';
class Model_Storage_Auth
{
const CLIENT_ID = "someuniquenumber.apps.googleusercontent.com";
const SERVICE_ACCOUNT_NAME = "myserviceaccountname@developer.gserviceaccount.com";
const KEY_FILE = "/supersecretpath/key.p12";
const ACCESS_TOKEN = 'access_token';
const APP_NAME = 'My App Name';
private $google_client;
function __construct()
{
$this->google_client = new Google_Client();
$this->google_client->setApplicationName(self::APP_NAME);
}
public function getToken()
{
if(!is_null($this->google_client->getAccessToken())){}
elseif(!is_null(Session::get(self::ACCESS_TOKEN, null)))
{
$this->google_client->setAccessToken(Session::get(self::ACCESS_TOKEN, null));
}
else
{
$scope = array();
$scope[] = 'https://www.googleapis.com/auth/devstorage.full_control';
$key = file_get_contents(self::KEY_FILE);
$this->google_client->setAssertionCredentials(new Google_AssertionCredentials(
self::SERVICE_ACCOUNT_NAME,
$scope,
$key)
);
$this->google_client->setClientId(self::CLIENT_ID);
Google_Client::$auth->refreshTokenWithAssertion();
$token = $this->google_client->getAccessToken();
Session::set(self::ACCESS_TOKEN, $token);
}
return $this->google_client->getAccessToken();
}
}
要檢查幾件事:
首先,我假設CLIENT_ID
和SERVICE_ACCOUNT_NAME
被設置為您的實際客戶端ID和服務帳戶名稱,而不僅僅是空字符串,對吧?
其次,您使用的是OAuth范圍https://www.googleapis.com/auth/prediction
但嘗試使用它來訪問GCS。 您可能希望使用只讀,讀寫或完全控制范圍,您可以在此處找到它。 例如,如果您想要讀寫訪問權限,則可以使用范圍https://www.googleapis.com/auth/devstorage.read_write
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.