Yii2 用户使用登录组件token验证

312 阅读1分钟

本文已参与「新人创作礼」活动,一起开启掘金创作之路。 请添加图片描述

当我在查阅 Yii文档的行为中,看到:

yii\behaviors\BlameableBehavior - 使用当前用户 ID 自动填充指定的属性。

在Laravel 中,获取认证用户调用的是Auth::user 即可获取当前登录用户。

在Yii中,用户这块文档中好像没有看到,做一下记录。

在继承的Controller中创建一个 guard ,在Yii 中用行为可实现:

    public function behaviors()
    {
        $behaviors = parent::behaviors();
        $behaviors['authenticator'] = [
            'class' => UserAuthenticate::className(),
        ];

        return $behaviors;
    }

在项目中 创建上述UserAuthenticate

use yii\filters\auth\AuthMethod;

class UserAuthenticate extends AuthMethod
{
    public $tokenParam = 'acc_token';
    public function authenticate($user, $request, $response)
    {
        $accessToken = $request->get($this->tokenParam);
        if (is_string($accessToken)) {
            $identity = $user->loginByAccessToken($accessToken, get_class($this));
            if ($identity !== null) {
                return $identity;
            }
        }
        if ($accessToken !== null) {
            $this->handleFailure($response);
        }
        return null;

    }
}

在控制器触发的时候,会调用该方法。

在 main.php 配置,提供验证的类。

'user' => [
    'identityClass' => 'api\models\User',
],
<?php
namespace api\models;
use Yii;
use yii\base\NotSupportedException;
use yii\behaviors\TimestampBehavior;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;
 
class User extends ActiveRecord implements IdentityInterface {
	 /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'users';
    }
    /**
     * @inheritdoc
     */
    public static function findIdentity($id)
    {
        return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
    }
 
    /**
     * @inheritdoc
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        return static::findOne(['access_token' => $token]);
    }
 
    //这个就是我们进行yii\filters\auth\QueryParamAuth调用认证的函数,下面会说到。
    public function loginByAccessToken($accessToken, $type) {
    	//查询数据库中有没有存在这个token
        return static::findIdentityByAccessToken($token, $type);
    }
 
    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByUsername($username)
    {
        return static::findOne(['username' => $username, 'status' => self::STATUS_ACTIVE]);
    }
 
 
    /**
     * @inheritdoc
     */
    public function getId()
    {
        return $this->getPrimaryKey();
    }
 
    /**
     * @inheritdoc
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }
 
    /**
     * @inheritdoc
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }
}

loginByAccessToken()这个函数是我们需要自己定义的函数,因为这个函数在yii\filters\auth\QueryParamAuth的认证类中会调用。 而findIdentityByAccessToken($token, $type = null)这个是接口函数,我们需要实现的,所以就在loginByAccessToken()这个函数中调用他去查询数据表中有没有对应的token存在,这个就是认证过程。

项目中可以使用 \Yii::$app->user->id 获取用户id

原文

参考: Yii官网 yii2框架-restful的请求参数token验证