rob006 / yii2-simple-auth
基于密钥提供简单认证的Yii 2扩展。
Requires
- yiisoft/yii2: 2.0.*
Suggests
- rob006/yii2-simple-auth-yii-authenticator: Helper for authenticate Request from yii2-httpclient package
This package is auto-updated.
Last update: 2024-09-04 22:42:02 UTC
README
基于密钥提供简单认证的Yii 2扩展。
该扩展提供了组件,用于轻松进行认证和验证HTTP请求。每个请求都获得一个唯一的令牌,带有过期时间,因此不需要在请求中发送密码或密钥 - 当不使用https时,这应该比基本访问认证更安全。
安装
安装此扩展的首选方式是通过composer。
运行以下命令之一:
php composer.phar require rob006/yii2-simple-auth
或者将以下内容添加到您的composer.json
文件的require部分:
"rob006/yii2-simple-auth": "^1.0"
to the require section of your config/web.php
文件。
用法
配置
您可以通过在config/web.php
和/或config/console.php
中的配置文件中设置参数来配置此扩展使用的默认密钥。
return [ ... 'params' => [ ... 'simpleauth' => [ 'secret' => 'mysecretkey', ], ], ];
这是可选的 - 您可以始终显式指定认证/验证的密钥。
认证(客户端)
使用官方yii2-httpclient
扩展时的认证
您可以使用yii2-simple-auth-yii-authenticator扩展简单地认证来自官方Yii 2 httpclient的Request
对象。
认证任何请求
您可以使用Authenticator
来认证任何请求,即使您不使用yii2-httpclient
包。例如,通过GET参数认证cURL请求
use rob006\simpleauth\Authenticator; $ch = curl_init(); $url = 'http://api.example.com/user/list/?ids=1,2,3,4'; $url .= '&' . Authenticator::PARAM_NAME . '=' . Authenticator::generateAuthToken($url); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $response = curl_exec($ch); curl_close($ch);
通过header认证cURL请求
use rob006\simpleauth\Authenticator; $ch = curl_init(); $url = 'http://api.example.com/user/list/?ids=1,2,3,4'; curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HTTPHEADER, [ Authenticator::HEADER_NAME . ': ' . Authenticator::generateAuthToken($url), ]); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); $response = curl_exec($ch); curl_close($ch);
验证(服务器端)
要检查请求是否有有效令牌,只需将操作过滤器添加到您的控制器中即可。
use rob006\simpleauth\ActionFilter; class MyController extends \yii\web\Controller { public function behaviors() { return [ ... 'simpleauth' => [ 'class' => ActionFilter::className(), ], ]; } ... }
您还可以为ActionFilter
配置一些设置。
use rob006\simpleauth\ActionFilter; use rob006\simpleauth\Authenticator; class MyController extends \yii\web\Controller { public function behaviors() { return [ ... 'simpleauth' => [ 'class' => ActionFilter::className(), // allow authentication only by header 'allowedMethods' => [ Authenticator::METHOD_HEADER, ], // set token timeout to 1 hour (by default it is 5 minutes) 'tokenDuration' => 3600, // override default header used for authentication 'headerName' => 'X-My-Custom-Header', // override params names used for send authentication token 'postParamName' => 'my_custom_token_param_name', 'getParamName' => 'my_custom_token_param_name', // custom secret used for validate authentication 'secret' => 'my-custom-secret-key', ], ]; } ... }
最后评论
确保为最终URL生成令牌,并且不执行请求的重定向。令牌是为确切地址生成的,所以
http://example.com/user/list/
https://example.com/user/list/
http://www.example.com/user/list/
http://example.com/user/list
的令牌将完全不同。
在使用POST请求时要小心。 Authenticator
和ActionFilter
只考虑URL,所有POST数据在认证和验证过程中都被忽略。这意味着一个令牌可能被多次用于不同的请求,这些请求具有不同的POST数据,但引用了相同的URL。