Yii user表中auth_key字段的作用

主要用途是通过cookie对用户进行身份验证.当您选择在登录时被记住时,这就是您被记住的方式.系统必须以某种方式识别并登录您.它可以将您的用户名和密码保存在cookie中(这是不安全的),也可以通过其他方式记住您.这是手段之一.登录到Yii应用程序后,查看它创建的_identity cookie,您将看到auth_key是cookie的一部分.

熟悉Yii的同学都知道Yii安装好后默认的会创建user表,表中有个字段 auth_key。这个字段是干啥的呢?以前没用到过,所以一直没有关心它,这次一次偶然的排除bug的过程中,发现了下面的代码

文件位置 vendor/yiisoft/yii2/web/User.php

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)) {
                Yii::warning("Invalid auth key attempted for user '$id': $authKey", __METHOD__);
            } else {
                return ['identity' => $identity, 'duration' => $duration];
            }
        }
    }
    $this->removeIdentityCookie();
    return null;
}

经过测试,每次登陆成功后Yii都会调用这个方法,用来获取保存或者删除cookie数据,从这个方法中可以看到,auth_key的主要作用是为了安全验证,毕竟cookie在浏览器中保存中,别人是可以篡改的(虽然Yii中的cookie本来就是httpOnly的,是无法直接通过js修改的),这个方法就保证了cookie无法被轻易篡改,因为cookie中保存着auth_key、id(用户ID)、duration(cookie过期时间),如果不做任何验证的话,用户可能通过浏览器直接篡改cookie中的用户ID,这样他就能随意登录任何用户的账号了。

而auth_key在数据库中保存着,别人无法知道,这样就算改了cookie中的用户ID,也无法登录用户账号,因为validateAuthKey方法会做验证,如果cookie中的auth_key和数据库中的不一致,就直接走下面的removeIdentityCookie方法了,直接清除cookie,退出登录状态了。

posted @ 2021-08-12 14:44  星云惊蛰  阅读(873)  评论(0)    收藏  举报