gud3 / yii2-rest-auth
为REST授权,旨在提高安全性。
1.0.0
2017-05-04 04:27 UTC
Requires
- ext-session: *
- yiisoft/yii2: ~2.0.0
This package is not auto-updated.
Last update: 2024-09-29 03:20:39 UTC
README
此扩展增加了对REST控制器请求之间的安全性。
工作原理:存在短(token)和长(series)密钥。短密钥每次都会变化,长密钥在整个授权期间保持不变。
然后它们合并成一个字符串,并附加到Authorization头。这些值由";"分隔
为了确认下一个请求,当"客户端"发送新的请求时,它会附加相同的Authorization头,并带上它接收到的数据。这个过程会一直持续到用户注销或密钥被盗。
当密钥被盗且盗贼使用用户的数据时 - 短密钥(token)在每次请求时都会变化。当真实用户发起请求时 - 系统会注意到长密钥(series)是相同的,但短密钥不匹配。在这种情况下,系统会删除Authorization,盗贼和真实用户都会被注销
对于数据存储,它使用ActiveRecord表。在这个表中保存了所有授权数据,会话的结束日期。会话存储在Redis中。
安装
安装此扩展的首选方式是通过 composer。
运行以下命令:
php composer.phar require --prefer-dist gud3/yii2-rest-auth "*"
或者将以下内容添加到你的 composer.json
文件的require部分:
"gud3/yii2-rest-auth": ">=1.0.0"
迁移代码行
yii migrate --migrationPath=@gud3/restAuth/migrations
需要
你需要覆盖'Users'表中的静态函数
public static function findIdentityByAccessToken($id, $type = null) { return static::find()->where(['id' => $id])->one() || false; }
用法
要使用此扩展,只需在你的控制器行为中添加以下代码:
public function behaviors() { $behaviors = parent::behaviors(); $auth = ['index']; //$auth = ['index', 'update', 'create', 'etc..']; $behaviors['authenticator']['class'] = \gud3\restAuth\CheckToken::className(); $behaviors['authenticator']['only'] = $auth; return $behaviors; }
检查头部中是否存在授权数据
public function behaviors() { $behaviors = parent::behaviors(); $auth = []; if (\gud3\restAuth\CheckToken::isAuth()) { array_push($auth, 'index', 'create'); } $behaviors['authenticator']['class'] = \gud3\restAuth\CheckToken::className(); $behaviors['authenticator']['only'] = $auth; return $behaviors; }
这是必要的,以便检查是否存在授权数据,然后检查它们,如果成功,则授权或通过系统而不需要授权,然后 Yii::$app->user->isGuest = true
更改存储
要将会话存储在Redis中,你需要
'components' => [ 'cache' => [ 'class' => 'yii\redis\Cache', ], ]