KnpUOAuth2ClientBundle 和 Google PHP API
KnpUOAuth2ClientBundle and Google PHP API
我有一个 Symfony 5 应用程序,它使用 KnpUOAuth2ClientBundle 通过 Google 帐户对用户进行身份验证。
我现在想集成 Google 驱动器 API 以便用户可以将文件上传到他的驱动器。
https://developers.google.com/drive/api/v3/quickstart/php
正在提供一些相关文档。
我想知道的是:如果用户已经通过身份验证(我有一个有效的用户访问令牌),我是否必须再次 运行 通过整个身份验证过程或者我是否可以使用之前的身份验证令牌由 KnpUOAuth2ClientBundle 生成?以及如何将此身份验证令牌作为对象获取?当我尝试通过 $client->getAccessToken() 获取它时,出现错误“无效状态”。
答案是:是的,您可以使用现有的登录令牌对 Google Drive API 等其他服务进行身份验证。您只需要现有的登录令牌作为字符串。
请注意,您可能需要像这样向登录名添加其他范围:
$clientRegistry
->getClient('google_main') // key used in config/packages/knpu_oauth2_client.yaml
->redirect([
'email',
'profile', // the scopes you want to access
Google_Service_Drive::DRIVE_FILE,
], []);
然后在您的 Google Drive Service 中,您可以像这样启动客户端:
/**
* Returns an authorized API client.
* @return Google_Client the authorized client object
*/
protected function initClient()
{
$user = $this->security->getUser();
$googleAccessToken = $user->getGoogleAccessToken();
$this->client->setApplicationName('MY APPLICATION');
$this->client->setScopes(Google_Service_Drive::DRIVE_METADATA_READONLY);
$this->client->setAccessType('offline');
$this->client->setPrompt('select_account consent');
$googleToken = [
'access_token' => $googleAccessToken,
'id_token' => $googleAccessToken,
// user is having a valid token from the login already
'created' => time() - 3600,
'expires_in' => 3600,
];
$this->client->setAccessToken($googleToken);
return $this->client;
}
我有一个 Symfony 5 应用程序,它使用 KnpUOAuth2ClientBundle 通过 Google 帐户对用户进行身份验证。
我现在想集成 Google 驱动器 API 以便用户可以将文件上传到他的驱动器。
https://developers.google.com/drive/api/v3/quickstart/php 正在提供一些相关文档。
我想知道的是:如果用户已经通过身份验证(我有一个有效的用户访问令牌),我是否必须再次 运行 通过整个身份验证过程或者我是否可以使用之前的身份验证令牌由 KnpUOAuth2ClientBundle 生成?以及如何将此身份验证令牌作为对象获取?当我尝试通过 $client->getAccessToken() 获取它时,出现错误“无效状态”。
答案是:是的,您可以使用现有的登录令牌对 Google Drive API 等其他服务进行身份验证。您只需要现有的登录令牌作为字符串。
请注意,您可能需要像这样向登录名添加其他范围:
$clientRegistry
->getClient('google_main') // key used in config/packages/knpu_oauth2_client.yaml
->redirect([
'email',
'profile', // the scopes you want to access
Google_Service_Drive::DRIVE_FILE,
], []);
然后在您的 Google Drive Service 中,您可以像这样启动客户端:
/**
* Returns an authorized API client.
* @return Google_Client the authorized client object
*/
protected function initClient()
{
$user = $this->security->getUser();
$googleAccessToken = $user->getGoogleAccessToken();
$this->client->setApplicationName('MY APPLICATION');
$this->client->setScopes(Google_Service_Drive::DRIVE_METADATA_READONLY);
$this->client->setAccessType('offline');
$this->client->setPrompt('select_account consent');
$googleToken = [
'access_token' => $googleAccessToken,
'id_token' => $googleAccessToken,
// user is having a valid token from the login already
'created' => time() - 3600,
'expires_in' => 3600,
];
$this->client->setAccessToken($googleToken);
return $this->client;
}