首页 > 解决方案 > yii2 身份 $authKey 返回数组

问题描述

我正在使用yii2. 当用户通过身份签出登录时,我自己创建一个令牌,自己将其写入 cookie 和数据库中。因此,一个用户可以从多个设备登录,单个用户可以在数据库中拥有多个令牌。

当我很长时间没有访问该站点时,会话和cookies死亡并出现错误,将$ authKey数组转换为字符串。它发生在课堂yii \ web \ User上。

protected function getIdentityAndDurationFromCookie(){
    $value = Yii::$app->getRequest()->getCookies()->getValue($this->identityCookie['name']);
    if ($value === null) {
        return null;
    }
    $data = json_decode($value, true);
    if (is_array($data) && count($data) == 3) {
        list($id, $authKey, $duration) = $data;
        /* @var $class IdentityInterface */
        $class = $this->identityClass;
        $identity = $class::findIdentity($id);
        if ($identity !== null) {
            if (!$identity instanceof IdentityInterface) {
                throw new InvalidValueException("$class::findIdentity() must return an object implementing IdentityInterface.");
            } elseif (!$identity->validateAuthKey($authKey)) {
                ERROR HERE:   Yii::warning("Invalid auth key attempted for user '$id': $authKey", __METHOD__);
            } else {
                return ['identity' => $identity, 'duration' => $duration];
            }
        }
    }
    $this->removeIdentityCookie();
    return null;
}

我在 Models\User 中的 validateAuthKey

public function validateAuthKey($authKey)
{
    $tokenArray = $this->getAuthKey();
    foreach($tokenArray as $item){
        if ($item->Token === $authKey){
            return true;
        }
    }
    return false;
}

在此方法中,从数据库中获取该用户的所有令牌并搜索匹配项

我显示$authKeyyii\web\User得到了一个难以理解的数组。数组有 30 个空对象。为什么$ authKey 是由数组组成的?

据我了解,它应该只包含我需要的 1 个令牌,我做错了什么?

标签: phpyii2

解决方案


推荐阅读