我需要基本的令牌认证.现在我甚至没有对它进行硬编码,但是这是我迄今为止所做的.
我有数据库表来保存我的单个令牌ApiAccess(id,access_token)
ApiAccess.PHP – 模型 – 注意:IDE在此第一行显示语法错误
- class ApiAccess extends base\ApiAccessBase implements IdentityInterface
- {
- public static function findIdentityByAccessToken($token,$type = null)
- {
- return static::findOne(['access_token' => $token]);
- }
- }
- \Yii::$app->user->enableSession = false;
我做了一个ApiController,每个后续的名词扩展
ApiController.PHP
- use yii\rest\ActiveController;
- use yii\filters\auth\HttpBasicAuth;
- use app\models\db\ApiAccess;
- class ApiController extends ActiveController
- {
- public function behaviors()
- {
- $behaviors = parent::behaviors();
- $behaviors['authenticator'] = [
- 'class' => HttpBasicAuth::className(),];
- return $behaviors;
- }
- }
就这样,访问浏览器中的api端点会提示输入用户名和密码.通过REST客户端请求显示访问错误.
如何正确地将HttpBasicAuth绑定到我的ApiAccess模型?
要么
如何硬编码api访问令牌? (第一选择显然是最好的)
1.当您向REST控制器添加行为时,启用基本身份验证:
- $behaviors['authenticator'] = [
- 'class' => HttpBasicAuth::className(),];
和你一样这是什么意思?这意味着您的应用程序将解析您的授权头.看起来像:
- Authorization : Basic base64(user:password)
这是yii2的伎俩.如果你仔细看代码,你会看到yii使用user_token,所以你的标题应该是:
- Authorization : Basic base64(access_token:)
如果要更改此行为,您可以自己解析此标题:
- $behaviors['authenticator'] = [
- 'class' => HttpBasicAuth::className(),'auth' => [$this,'auth']
- ];
- ....
- public function auth($username,$password)
- {
- return \app\models\User::findOne(['login' => $username,'password' => $password]);
- }
第二件事要做您必须从identityInterface实现findIdentityByAccessToken()函数.
为什么你的IDE抱怨?
- class User extends ActiveRecord implements IdentityInterface
以下是您的用户类声明应该如何看待.
从您的实施和结构:
- public static function findIdentityByAccessToken($token,$type = null)
- {
- return static::findOne(['access_token' => $token]);
- }
你不返回实现标识接口的类的对象.
如何正确使用?
将列access_token添加到用户表中,并返回您的用户模型(您可以看看它必须如何看 – https://github.com/yiisoft/yii2-app-advanced/blob/master/common/models/User.php)
如果这样做 – 默认代码将与您的findIdentityByAccessToken()实现一起使用.
如果您不想向用户添加字段表 – 使用user_id,access_token字段创建新字段.那么你的实现应该是:
- public static function findIdentityByAccessToken($token,$type = null)
- {
- $apiUser = ApiAccess::find()
- ->where(['access_token' => $token])
- ->one();
- return static::findOne(['id' => $apiUser->user_id,'status' => self::STATUS_ACTIVE]);
- }
希望能覆盖你的所有问题.