nyan02 / kphp_oauth2_google
为 KPHP OAuth2 客户端提供的 Google OAuth 2.0 客户端提供程序
Requires
- php: >=7.4
- nyan02/kphp_oauth2_client: ^1.0
- vkcom/kphp-polyfills: ^1.0
This package is auto-updated.
Last update: 2024-09-14 14:34:50 UTC
README
此包为 KPHP 提供了 Google OAuth 2.0 支持
安装
要安装,请使用 composer
composer require nyan02/kphp_oauth2_google
用法
用法类似于 KPHP OAuth 客户端,使用 nyan02\kphp_oauth2_client\Provider\Google 作为提供程序。
您需要创建一个新的 Provider 对象,指定 google-client-id、google-client-secret 和 callback-url。
如果您想限制访问并仅允许您的 G Suite/Google Apps for Business 帐户(企业电子邮件)上的用户访问,您可以配置提供程序来设置托管域。
下面是一个示例。
授权码示例
<?php
use nyan02\kphp_oauth2_client\Grant\AuthorizationCode;
use nyan02\kphp_oauth2_client\Provider\Google;
require_once __DIR__ . '/vendor/autoload.php';
$provider = new Google('{google-client-id}',
'{google-client-secret}',
'https://example.com/callback-url',
);
$provider->setHostedDomain('example.com'); // optional; used to restrict access to users on your G Suite/Google Apps for Business accounts
if (!empty($_GET['error'])) {
// Got an error, probably user denied access
exit('Got error.');
} elseif (empty($_GET['code'])) {
// If we don't have an authorization code then get one
$params = $provider->getAuthorizationParameters();
$authUrl = $provider->getAuthorizationUrl($params);
// $_SESSION['oauth2state'] = $provider->getState();
header('Location: ' . $authUrl);
exit;
} else {
// Try to get an access token (using the authorization code grant)
$grant = new AuthorizationCode($provider->getClientId(), $provider->getClientSecret(), $provider->getRedirectUri());
$token = $provider->getAccessToken($grant, ['code' => $_GET['code']]);
// Optional: Now you have a token you can look up a users profile data
try {
// We got an access token, let's now get the owner details
$ownerDetails = $provider->getResourceOwner($token);
// Use these details to create a new profile
printf('Hello %s!<br>', $ownerDetails->name);
// Use this to interact with an API on the users behalf
echo $token->getToken().'<br>';
// Use this to get a new access token if the old one expires
echo $token->getRefreshToken().'<br>';
// Unix timestamp at which the access token expires
echo $token->getExpires().'<br>';
} catch (Exception $e) {
// Failed to get user details
exit('Something went wrong: ' . $e->getMessage());
}
}
授权码流程
配置提供程序后,我们想要获取授权码。我们使用 getAuthorizationParameters() 方法从提供程序获取参数,包括权限作用域和其他生成 AuthorizationUrl 所需的信息。
然后我们使用 getAuthorizationUrl($params) 方法生成 AuthorizationUrl,并传递我们之前获取的参数。现在我们有了 URL,我们可以将用户重定向到提供程序的授权页面。
一旦我们得到了授权码,我们创建一个用于它的占位符类
new AuthorizationCode($provider->getClientId(), $provider->getClientSecret(), $provider->getRedirectUri())
并将其与获取的代码一起传递给 getAccessToken 方法。
$token = $provider->getAccessToken($grant, ['code' => $_GET['code']]);
现在我们有资源的访问令牌了。
获取资源拥有者信息
有了访问令牌,我们现在可以访问用户信息。
$ownerDetails = $provider->getResourceOwner($token);
为 GoogleResourceOwner 实现的方法是 getId() 和 toJSON()。所有类属性都是公开的,因此您可以直接访问它们。GoogleResourceOwner 有以下属性:sub、name、given_name、family_name、locale、hd、email、picture。