hosannahighertech/yii2-oauth2-server
最新稳定版本:v1.0.1
Composer 安装命令:
composer require hosannahighertech/yii2-oauth2-server
包简介
OAuth2 Server for PHP a fork of filsh/yii2-oauth2-server
关键字:
README 文档
README
A wrapper for implementing an OAuth2 Server(https://github.com/bshaffer/oauth2-server-php). This is a fork of https://github.com/Filsh/yii2-oauth2-server. I decided to fork it after a long standing issue of branches not being resolved at original repo. There is no guarantee that the two will remain compartible so check out things to see if there is anything broke while transiting.
Installation
The preferred way to install this extension is through composer.
Either run
php composer.phar require --prefer-dist hosannahighertech/yii2-oauth2-server "*" or add
"hosannahighertech/yii2-oauth2-server": "1.0.*"
to the require section of your composer.json.
To use this extension, simply add the following code in your application configuration:
'bootstrap' => ['oauth2'], 'modules' => [ 'oauth2' => [ 'class' => 'filsh\yii2\oauth2server\Module', 'tokenParamName' => 'accessToken', 'tokenAccessLifetime' => 3600 * 24, 'storageMap' => [ 'user_credentials' => 'common\models\User', ], 'grantTypes' => [ 'user_credentials' => [ 'class' => 'OAuth2\GrantType\UserCredentials', ], 'refresh_token' => [ 'class' => 'OAuth2\GrantType\RefreshToken', 'always_issue_new_refresh_token' => true ] ] ] ]
Configure User class
common\models\User - user model implementing an interface \OAuth2\Storage\UserCredentialsInterface, so the oauth2 credentials data stored in user table. Make sure you implement:
-
public function checkUserCredentials($username, $password)which Checks the supplied username and password for validity and returns TRUE if the username and password are valid, and FALSE if it isn't. -
public function getUserDetails($username)which returns array of the associated "user_id" and optional "scope" values something like this:
[ "user_id" => USER_ID, // REQUIRED user_id to be stored with the authorization code or access token "scope" => SCOPE // OPTIONAL space-separated list of restricted scopes ]
Additional OAuth2 Flags:
enforceState - Flag that switch that state controller should allow to use "state" param in the "Authorization Code" Grant Type
allowImplicit - Flag that switch that controller should allow the "implicit" grant type
The next step your shold run migration
yii migrate --migrationPath=@vendor/hosannahighertech/yii2-oauth2-server/migrations this migration create the oauth2 database scheme and insert test user credentials testclient:testpass for http://fake/
add url rule to urlManager
'urlManager' => [ 'rules' => [ 'POST oauth2/<action:\w+>' => 'oauth2/rest/<action>', ... ] ]
Usage
To use this extension, simply add the behaviors for your base controller:
use yii\helpers\ArrayHelper; use yii\filters\auth\HttpBearerAuth; use yii\filters\auth\QueryParamAuth; use filsh\yii2\oauth2server\filters\ErrorToExceptionFilter; use filsh\yii2\oauth2server\filters\auth\CompositeAuth; class Controller extends \yii\rest\Controller { /** * @inheritdoc */ public function behaviors() { return ArrayHelper::merge(parent::behaviors(), [ 'authenticator' => [ 'class' => CompositeAuth::className(), 'authMethods' => [ ['class' => HttpBearerAuth::className()], ['class' => QueryParamAuth::className(), 'tokenParam' => 'accessToken'], ] ], 'exceptionFilter' => [ 'class' => ErrorToExceptionFilter::className() ], ]); } }
Create action authorize in site controller for Authorization Code
https://api.mysite.com/authorize?response_type=code&client_id=TestClient&redirect_uri=https://fake/
/** * SiteController */ class SiteController extends Controller { /** * @return mixed */ public function actionAuthorize() { if (Yii::$app->getUser()->getIsGuest()) return $this->redirect('login'); /** @var $module \filsh\yii2\oauth2server\Module */ $module = Yii::$app->getModule('oauth2'); $response = $module->handleAuthorizeRequest(!Yii::$app->getUser()->getIsGuest(), Yii::$app->getUser()->getId()); /** @var object $response \OAuth2\Response */ Yii::$app->getResponse()->format = \yii\web\Response::FORMAT_JSON; return $response->getParameters(); } }
For More on Requests and responses as well as explanations for Oauth Grant types see excellet tutorial by Jenkov here: http://tutorials.jenkov.com/oauth2/
Also if you set allowImplicit => true you can use Implicit Grant Type - see more
Request example:
https://api.mysite.com/authorize?response_type=token&client_id=TestClient&redirect_uri=https://fake/cb
With redirect response:
https://fake/cb#access_token=2YotnFZFEjr1zCsicMWpAA&state=xyz&token_type=bearer&expires_in=3600
JWT Tokens
If you want to get Json Web Token (JWT) instead of convetional token, you will need to set 'useJwtToken' => true in module and then define two more configurations: 'public_key' => 'app\storage\PublicKeyStorage' which is the class that implements PublickKeyInterface and 'access_token' => 'OAuth2\Storage\JwtAccessToken' which implements JwtAccessTokenInterface.php. The Oauth2 base library provides the default access_token which works great. Just use it and everything will be fine.
Here is a sample class for public key implementing PublickKeyInterface. Make sure that paths to private and public keys are correct. You can generate them with OpenSSL tool with two steps (Thanks to (Rietta)[https://rietta.com/blog/2012/01/27/openssl-generating-rsa-key-from-command/]):
-
openssl genrsa -des3 -out privkey.pem 2048 -
openssl rsa -in privkey.pem -outform PEM -pubout -out pubkey.pem
Note that you can copy contents of the files and paste the long strings in class variables. It is nasty but it works fine if that is what you want.
<?php namespace app\security\storage; class PublicKeyStorage implements \OAuth2\Storage\PublicKeyInterface{ private $pbk = null; private $pvk = null; public function __construct() { $pvkText = file_get_contents(dirname(__FILE__).'/../keys/privkey.pem'); $this->pvk = openssl_get_privatekey($pvkText, 'YOUR_PASSPHRASE_IF_ANY'); $this->pbk = file_get_contents(dirname(__FILE__).'/../keys/pubkey.pem'); } public function getPublicKey($client_id = null){ return $this->pbk; } public function getPrivateKey($client_id = null){ return $this->pvk; } public function getEncryptionAlgorithm($client_id = null){ return "RS256"; } }
For more, see https://github.com/bshaffer/oauth2-server-php
hosannahighertech/yii2-oauth2-server 适用场景与选型建议
hosannahighertech/yii2-oauth2-server 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 49.1k 次下载、GitHub Stars 达 15, 最近一次更新时间为 2026 年 01 月 04 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「oauth」 「oauth2」 「module」 「extension」 「yii」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 hosannahighertech/yii2-oauth2-server 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 hosannahighertech/yii2-oauth2-server 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 hosannahighertech/yii2-oauth2-server 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
WeChat OAuth SDK
Ory-Hydra OAuth 2.0 Client Provider for The PHP League OAuth2-Client
Library for ORCID web services
A lightweight and powerful OAuth 2.0 authorization and resource server library with support for all the core specification grants. This library will allow you to secure your API with OAuth and allow your applications users to approve apps that want to access their data from your API.
Email Toolkit Plugin for CakePHP
bootstrap select field module implementing http://silviomoreto.github.io/bootstrap-select/
统计信息
- 总下载量: 49.1k
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 16
- 点击次数: 14
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2026-01-04