the-real-start / yii2-oauth2-server-tools
一套针对
Requires
- alegz/yii2-oauth2-server: ~2.2
- the-real-start/yii2-jsend-response: ^0.1.4
- yiisoft/yii2: >=2.0.6
This package is not auto-updated.
Last update: 2024-09-26 03:41:19 UTC
README
一组简单的工具,用于基于 alegz/yii2-oauth2-server
包构建API。
安装
通过命令行
composer require the-real-start/yii2-oauth2-server-tools
或在 composer.json 的要求部分添加 lime
"require": {
...
"the-real-start/yii2-oauth2-server-tools": "*"
...
}
用法
包命名空间: TRS\yii2\oauth2server\tools
包提供了设置 oauth2-server 的 5 个类
- 抽象类 AppIdentity
- 抽象类 User
- 类 ErrorHandler
- 类 AccessRules
- 类 JsonHttpException
AppIdentity
抽象类,用于 client credentials
grant_type(详细信息请见https://tools.ietf.org/html/rfc6749)。
您应该为您的 AppIdentity
类版本声明 getIsPublic 方法。以下是一个示例
<?php
namespace common\components;
use common\components\enums\Scope;
use TRS\yii2\oauth2server\tools\oauth2\AppIdentity as BaseAppIdentity
class AppIdentity extends BaseAppIdentity
{
/**
* @inheritdoc
*/
abstract public function isPublicClient($client_id){
$app = self::findByClientId($client_id);
return !!$app && $app->scope == Scope::_PUBLIC;
}
}
使用 yii2-oauth2-server
模块的设置示例
modules' => [
...
'oauth2' => [
'class' => \filsh\yii2\oauth2server\Module::className(),
...
'storageMap' => [
...
'client_credentials' => \common\components\AppIdentity::class,
],
...
],
...
],
User
这个抽象类扩展了 yii\web\User
,增加了 getIsPublic
方法,并改变了注销用户的逻辑。
此类需要为 User
声明 getIsPublic
方法
类示例
<?php
namespace common\components;
use common\enums\Scope;
use TRS\yii2\oauth2server\tools\oauth2\User as BaseUser;
class User extends BaseUser
{
/**
* @ingeritdoc
*/
public function getIsPublic()
{
/** @var \common\models\User $identity */
$identity = $this->getIdentity(false);
return ( $identity->scope == Scope::_PUBLIC );
}
}
设置示例
'components' => [
...
'user' => [
'class' => \common\components\User::className(),
'identityClass' => \common\models\User::className(),
'enableAutoLogin' => true,
],
...
],
ErrorHandler
一个简单的错误处理程序,专为与 API 一起使用而设计。
在 yii2 的 main.php
配置文件的 components
部分设置示例
...
'errorHandler' => [
'class' => \v1\components\oauth2\rest\ErrorHandler::className(),
],
...
AccessRules
yii2 AccessRule
的扩展版本。增加了对用户范围过滤的支持。
规则示例
public function accessRules()
{
return [
[
'allow' => true,
'roles' => [ '@' ],
'actions' => [ 'registration', 'send-recovery-email', 'reset-password', 'check-reset-token' ],
'scopes' => [ Scope::_PUBLIC ],
],
];
}
设置示例
public function behaviors()
{
$behaviors = parent::behaviors();
...
$behaviors = ArrayHelper::merge(
$behaviors,
[
...
'access' => [
'class' => AccessControl::className(),
'rules' => $this->accessRules(),
'ruleConfig' => ['class' => AccessRule::class],
],
...
]
);
return $behaviors;
}
在此示例和上一个示例中,accessRules 被声明为基本控制器中的抽象方法。
JsonHttpException
它是一个简单的 HTTPException 包装器,可以接受数组作为消息。
数组将被转换为 json。
专为与 ErrorHandler 一起使用而设计,但您也可以自由地将其应用到您的工具中。
小示例
/** @var array */
$errors = $model->getErrors();
throw new JsonHttpException(400, $errors);
参与和开发
希望您会认为这组工具很有用。
如果您有建议,请欢迎在 GitHub 上的 issues 中提出。
如果您想改进这个包,请随时提交 pull requests。