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

请添加图片描述

当我在查阅 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验证

本作品采用《CC 协议》,转载必须注明作者和本文链接
讨论数量: 0
(= ̄ω ̄=)··· 暂无内容!

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!
未填写
文章
37
粉丝
16
喜欢
132
收藏
113
排名:327
访问:2.9 万
私信
所有博文
社区赞助商