fotografde / oauth-client
适用于 oauth-server 的 Oauth 客户端提供者
Requires
- php: >=5.6
- desarrolla2/cache: ^2.1
- league/oauth2-client: ^2.3
Requires (Dev)
- mockery/mockery: ^0.9.4
- php-coveralls/php-coveralls: ^2.0
- phpunit/phpunit: ~4.0
This package is auto-updated.
Last update: 2024-08-28 16:16:48 UTC
README
Getphoto OAuth 2.0 客户端提供者
本包为 PHP League 的 OAuth 2.0 客户端 提供Getphoto OAuth 2.0 支持。
安装
要安装,请使用 composer
$ composer require getphoto/oauth-client
使用方法
! 注意! 对于需要缓存的常用用例,请检查 缓存令牌
使用方法与 The League 的 OAuth 客户端相同,使用 \Getphoto\Oauth2\OauthProvider
作为提供者。可以在此找到使用不同授权类型实现的简单前端客户端应用程序 这里
客户端凭证授权
<?php $provider = new Getphoto\Oauth2\OauthProvider([ 'clientId' => 'testclient', 'clientSecret' => 'testclient' ]); try { // Try to get an access token using the client credentials grant. $token=$provider->getAccessToken( 'client_credentials', ['scope'=>'testscope'] ); } catch (\Exception $e) { // Failed to get the access token exit($e->getMessage()); } ?>
密码授权
<?php $provider = new Getphoto\Oauth2\OauthProvider([ 'clientId' => 'testclient', 'clientSecret' => 'testclient' ]); try { // Try to get an access token using the password grant. $token=$provider->getAccessToken( 'password', [ 'scope'=>'testscope', 'username' => 'test@test.com', 'password' => 'password' ])); } catch (\Exception $e) { // Failed to get the access token exit($e->getMessage()); } //we can then use getResorceOwner to get user data $data['resource_owner']=$provider->getResourceOwner($token); $username=$data['resource_owner']->getName(); ?>
密码 FTP 授权
<?php $provider = new Getphoto\Oauth2\OauthProvider([ 'clientId' => 'testclient', 'clientSecret' => 'testclient' ]); try { // Try to get an access token using the password grant. $token=$provider->getAccessToken( 'password_ftp', [ 'scope'=>'testscope', 'username' => 'test', 'password' => 'password' ])); } catch (\Exception $e) { // Failed to get the access token exit($e->getMessage()); } //we can then use getResorceOwner to get user data $data['resource_owner']=$provider->getResourceOwner($token); $username=$data['resource_owner']->getName(); ?>
授权码授权
<?php $provider=new OauthProvider([ 'clientId' => 'testclient', 'clientSecret' => 'testclient', 'redirectUri' => 'here_goes_current_url' ]); // If we don't have an authorization code then get one if (!isset($_GET['code'])) { // Fetch the authorization URL from the provider; this returns the // urlAuthorize option and generates and applies any necessary parameters // (e.g. state). $authorizationUrl = $provider->getAuthorizationUrl(['scope' => 'testscope']); // Get the state generated for you and store it to the session. $_SESSION['oauth2state'] = $provider->getState(); // Redirect the user to the authorization URL. header('Location: ' . $authorizationUrl); exit; // Check given state against previously stored one to mitigate CSRF attack } elseif (empty($_GET['state']) || ($_GET['state'] !== $_SESSION['oauth2state'])) { // State is invalid, possible CSRF attack in progress unset($_SESSION['oauth2state']); exit('Invalid state'); } else { try { // Try to get an access token using the authorization code grant. $token=$provider->getAccessToken( 'authorization_code', [ 'scope' => 'testscope', 'code' => $_GET['code'] ]); } catch (\Exception $e) { // Failed to get the access token exit('ERROR: '.$e->getMessage()); } } //we can then use getResorceOwner to get user data $data['resource_owner']=$provider->getResourceOwner($token); $username=$data['resource_owner']->getName(); ?>
有关这些授权和用例的更详细描述,请参阅核心包 文档。
获取资源所有者数据
可以使用 ResourceOwner
类方便地获取资源所有者数据(用户数据)
<?php $resource_owner=$provider->getResourceOwner($token); $user_name=$resource_owner->getName(); $user_email=$resource_owner->getEmail(); $user_id=$resource_owner->getId(); $user_data=$resource_owner->getUserData(); //gets related user data /* [ "id" => 7053 "name" => "tre" "email" => "test@test.com" "created_at" => null "updated_at" => "2017-05-15 10:03:10" "core_user_id" => 20128 "photographer_id" => 47911 ] */ $user_scopes=$resource_owner->getScopes(); //get scopes token hass access to /* [ "payment.settings.read" => [ "id" => "payment.settings.read" "description" => "Some nice description" ] ] */ ?>
缓存令牌
从我们看到的几个用例中,我们发现缓存令牌逻辑是常见的并且非常相似。这就是为什么这个包现在提供方便的缓存令牌方法 - getAccessTokenSmart
(如果令牌获取失败,它还会执行一个额外的回退调用并记录错误)
OauthProvider 构造函数选项
<?php public function __construct(array $options = [], array $collaborators = []) ?>
通过构造函数,您可以设置新的选项
cacheOn
bool - 是否在 getAccessTokenSmart 中使用缓存(默认为 true)cacheSafeInterval
float - 在令牌过期前多少分钟续订令牌(默认为 5)cachePrefix
string - 如果在相同系统但不同用例中使用提供者,则重要设置(默认为 '')
以及额外的合作伙伴
logger
- 实现 LoggerInterface 的日志类实例 - 默认为简单的文件记录器 Loggercacher
- 实现 CacherInterface 的缓存类实例 - 默认为简单的文件缓存器 Cacher
getAccessTokenSmart 方法
与 getAccessToken
相同的参数,但带有额外的选项,因此您可以在构造函数中覆盖选项(仅针对此调用) - cacheOn
、cacheSafeInterval
、cachePrefix
。
clearTokenCache 方法
<?php public function clearTokenCache($prefix = '') ?>
当您想忘记缓存的令牌时使用此方法。使用 $prefix
(要清除令牌的)参数可以覆盖构造函数设置。
getAccessTokenSmart 的示例用法
以下是来自我们核心系统的示例用法,该系统调用 OAuth 服务器以同步用户更改
1. 构造提供者
<?php $this->oauthProvider = new OauthProvider( [ 'clientId' => 'some_clinet', 'clientSecret' => 'some_secret', 'cachePrefix' => 'userApi' ], [ 'cacher' => new OauthCakeCacher(), //implemented using native cake cache 'logger' => new OauthCakeLogger() //implemented using native cake log ] ); ?>
2. 获取令牌
<?php $token = $this->oauthProvider->getAccessTokenSmart('client_credentials', [ 'scope' => 'some_scope' ]); ?>
3. 调用受保护 API 并在无效令牌时清除令牌缓存
<?php ... //some call to protected API with your token goes here $response = $request->send(); ... //clear token if invalid if ($response->getStatusCode() == 403 || $response->getStatusCode() == 401) { //forget invalid token $this->oauthProvider->clearTokenCache(); } ?>
注意:有关 CacherInterface 的会话实现示例,请参阅核心系统中的 OAuth 库。在 Jobs 插件的 ApiComponent 中的使用
注销
现在有一种登出方法可以使令牌过期,您应该在您的登出流程中实现它,以在我们的认证服务器上节省一些资源
$this->oauthProvider->expireAccessToken("g2WvRwXDQrIEmi0Qkcs0Qt11ch4AbkW2Yakh8BqI");
测试中
$ ./vendor/bin/phpunit vendor/getphoto/oauth-client