首页 > 解决方案 > 如何在 PHP 中使用 OAuth2 对 Google Cloud API 进行身份验证

问题描述

我正在尝试使用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 一起使用包 ( https://github.com/googleapis/google-cloud-php ),例如上面的 BillingClient。但我正在努力解决如何

编辑

除此之外:在下面的 jdp 回答中,他使用了“凭据”配置键。请注意 CloudBillingGapicClient 来源中的这条注释:“此外,此选项还可以接受预先构造的 \Google\Auth\FetchAuthTokenInterface 对象或 \Google\ApiCore\CredentialsWrapper} 对象”。当我查看 Google 的 Auth 包中的 OAuth2 类时,我发现它实现了 FetchAuthTokenInterface。所以看起来它应该可以用来传递 OAuth 凭据。我只是不知道怎么做。

标签: phpapigoogle-cloud-platformoauth-2.0

解决方案


您可以创建服务帐户并下载凭据文件,然后配置应用程序默认凭据。从那里客户端将自动进行身份验证。

您还可以在创建客户端时直接提供凭据:

$client = new CloudBillingClient([
    'credentials' => '/path/to/keyfile.json'
]);

$accounts = $client->listBillingAccounts();

foreach ($accounts as $account) {
    print('Billing account: ' . $account->getName() . PHP_EOL);
}

推荐阅读