【发布时间】:2020-04-11 02:17:34
【问题描述】:
我正在尝试使用 https://github.com/googleapis/google-cloud-php 包与 Google Cloud API 交互。
例如,我在这里发出一个账单帐户请求:
$client = new CloudBillingClient();
$accounts = $client->listBillingAccounts();
foreach ($accounts as $account) {
print('Billing account: ' . $account->getName() . PHP_EOL);
}
这显然不起作用,因为没有凭据,并引发错误:
Google\ApiCore\ValidationException
Could not construct ApplicationDefaultCredentials
那么,我如何进行身份验证才能使计费查询正常工作?需要明确的是,我可以使用另一个 OAuth2 库来获取 access_token,没有问题。例如在这个 Laravel 控制器中:
use League\OAuth2\Client\Provider\Google as GoogleProvider;
class GoogleAuthController extends Controller
{
public function index()
{
$provider = new GoogleProvider([
'clientId' => $clientId,
'clientSecret' => $clientSecret,
'redirectUri' => $redirectUri // will use this same url 'index'
]);
$authUrl = $provider->getAuthorizationUrl([
'scope' => [
'https://www.googleapis.com/auth/cloud-platform'
]
]);
// This is the first request for authorization
if (empty($_GET['code']))
{
session()->put('oauth2state', $provider->getState());
return redirect($authUrl);
}
// This is the returned request from Google
else
{
$token = $provider->getAccessToken('authorization_code', [
'code' => $_GET['code']
]);
// I HAVE A TOKEN NOW! I can do a request using Guzzle, like below, and it works fine.
// But surely Google's package should allow me to do this?!?!?
$response = Http::get('https://cloudresourcemanager.googleapis.com/v1/projects', [
'access_token' => $token
]);
return $response;
}
}
}
但是,我想利用 Google 已经构建的库的强大功能。
查看 PHP 的 Google Auth 包 (https://github.com/googleapis/google-auth-library-php) 我看到很多提到 OAuth,并且似乎可能将该库生成的凭据与 Google Cloud 包一起使用 (@987654323 @),就像上面的 BillingClient 一样。但我正在为如何而苦苦挣扎。
编辑
除此之外:在下面的 jdp 回答中,他使用了“凭据”配置键。请注意 CloudBillingGapicClient 来源中的这条注释:“此外,此选项还可以接受预先构造的 \Google\Auth\FetchAuthTokenInterface 对象或 \Google\ApiCore\CredentialsWrapper} 对象”。当我查看 Google 的 Auth 包中的 OAuth2 类时,我发现它实现了 FetchAuthTokenInterface。所以看起来它应该可以用来传递 OAuth 凭据。我只是不知道怎么做。
【问题讨论】:
-
据我了解,您在项目中创建了应用凭据。您只能获得项目的访问令牌,不能访问我的项目。访问我的项目的唯一方法是创建一个服务帐户,我应该在我的项目中添加这个具有 wright 权限的服务帐户。否则,您将无法访问我的项目。
标签: php api google-cloud-platform oauth-2.0