andres-ml / cakephp-oauth2
使用league/oauth2-client家族实现CakePHP 3.6认证
v2.0.0
2023-07-25 10:33 UTC
Requires (Dev)
- cakephp/cakephp: ^4.0
- cakephp/cakephp-codesniffer: ^2.0
- league/oauth2-github: ^0.2
- phpunit/phpunit: ^8.0
This package is auto-updated.
Last update: 2024-09-25 12:46:11 UTC
README
使用 CakePHP 3 认证,通过 league/oauth2-client。
安装
使用 Composer
composer require muffin/oauth2:dev-master
然后需要加载插件。可以使用shell命令
bin/cake plugin load Muffin/OAuth2
或者手动将下面的语句添加到 bootstrap.php
Plugin::load('Muffin/OAuth2');
等等,你还没有完成。此插件不会要求任何客户端。你需要自己完成
composer require "league/oauth2-github:^1.0@dev"
使用方法
首先,定义提供者
// either in `config/bootstrap.php` Configure::write('Muffin/OAuth2', [ 'providers' => [ 'github' => [ 'className' => 'League\OAuth2\Client\Provider\Github', // all options defined here are passed to the provider's constructor 'options' => [ 'clientId' => 'foo', 'clientSecret' => 'bar', ], 'mapFields' => [ 'username' => 'login', // maps the app's username to github's login ], // ... add here the usual AuthComponent configuration if needed like fields, etc. ], ], ]); // or in `src/Controller/AppController.php` $this->loadComponent('Auth', [ 'authenticate' => [ // ... 'Muffin/OAuth2.OAuth' => [ 'providers' => [ // the array from example above ], ], ], ]);
授权成功后,如果用户没有本地实例,将触发一个事件(Muffin/OAuth2.newUser)。使用它创建用户如下
// bootstrap.php use Cake\Event\Event; use Cake\ORM\TableRegistry; EventManager::instance()->on('Muffin/OAuth2.newUser', [TableRegistry::get('Users'), 'createNewUser']); // UsersTable.php use Cake\Event\Event; use League\OAuth2\Client\Provider\AbstractProvider; public function createNewUser(Event $event, AbstractProvider $provider, array $data) { $entity = $this->newEntity($data); $this->save($entity); return $entity->toArray(); // user data to be used in session }
最后,一旦收到令牌,将触发 Muffin/OAuth2.afterIdentify 事件。例如,使用此事件更新您的本地令牌
// bootstrap.php use Cake\Event\Event; use Cake\ORM\TableRegistry; EventManager::instance()->on('Muffin/OAuth2.afterIdentify', [TableRegistry::get('Tokens'), 'createOrUpdate']); // TokensTable.php use Cake\Event\Event; use League\OAuth2\Client\Provider\AbstractProvider; public function createOrUpdate(Event $event, AbstractProvider $provider, array $data) { // ... return; // void }
接下来,您需要创建一个所有提供者都将使用的路由
// config/routes.php Router::connect( '/oauth/:provider', ['controller' => 'users', 'action' => 'login'], ['provider' => implode('|', array_keys(Configure::read('Muffin/OAuth2.providers')))] );
现在,如果您已经阅读了书籍的 AuthComponent 文档,您应该熟悉如何将其添加到新认证对象中
// src/Controller/AppController.php $this->load('Auth', [ 'authenticate' => [ 'Form', 'Muffin/OAuth2.OAuth', ] ]);
补丁与功能
- 分支
- 修改,修复
- 测试 - 这很重要,所以不要无意中破坏它
- 提交 - 不要修改许可,todo,版本等。(如果您做了修改,请将它们放入自己的提交中,以便我在拉取时可以忽略)
- 拉取请求 - 主题分支的额外加分
为了确保您的PR被上游考虑,您必须遵循 CakePHP 编码标准。
错误与反馈
http://github.com/usemuffin/oauth2/issues
许可证
版权 (c) 2015, Use Muffin,许可协议为 MIT 许可证。