Yii2 强制用户退出登录状态方法

分类:Yii2 |

对于Yii2 强制用户退出登录状态: 

解决方法需两步: 

a. 清理session : 如果是在文件, 删除对应的runtime/session里的 数据, 或清理 redis 里的数据

b. 修改main-local.php 里的 cookieValidationKey 里的值, 'request' => ['cookieValidationKey' => 'C41py_RDUh80fenJM99Gj8ocLR4nmeLjxx'],


原以为Yii2 登录仅限于 session

3479a11f941a80a55b1d6fe9fc6c9e825f4af3fc2b51dceaae7aa54815ceb321a:2:{i:0;s:7:"id-site";i:1;s:25:"[11,"1288070547",2592000]";}


yii\base\Security 类中的方法校验:


public function validateData($data, $key, $rawHash = false)

    {

        $test = @hash_hmac($this->macHash, '', '', $rawHash);

        if (!$test) {

            throw new InvalidConfigException('Failed to generate HMAC with hash algorithm: ' . $this->macHash);

        }

        $hashLength = StringHelper::byteLength($test);

        if (StringHelper::byteLength($data) >= $hashLength) {

            $hash = StringHelper::byteSubstr($data, 0, $hashLength);

            $pureData = StringHelper::byteSubstr($data, $hashLength, null);

            

            # $key 来自于

            # 配置文件中的  'components' => [

//            'request' => [

//                // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation

//                'cookieValidationKey' => 'C41py_RDUh80fenJM99Gj8ocLR4nmeLj',

//            ],

            $calculatedHash = hash_hmac($this->macHash, $pureData, $key, $rawHash); 


            if ($this->compareString($hash, $calculatedHash)) {

                return $pureData;

            }

        }


        return false;

    }




yii\web\User 中的方法来

    protected function renewAuthStatus()

    {

        $session = Yii::$app->getSession();

        # 取得对应的用户ID 

        $id = $session->getHasSessionId() || $session->getIsActive() ? $session->get($this->idParam) : null;


        if ($id === null) {

            $identity = null;

        } else {

            /* @var $class IdentityInterface */

            $class = $this->identityClass;

            $identity = $class::findIdentity($id);

        }


        $this->setIdentity($identity);


        if ($identity !== null && ($this->authTimeout !== null || $this->absoluteAuthTimeout !== null)) {

            $expire = $this->authTimeout !== null ? $session->get($this->authTimeoutParam) : null;

            $expireAbsolute = $this->absoluteAuthTimeout !== null ? $session->get($this->absoluteAuthTimeoutParam) : null;

            if ($expire !== null && $expire < time() || $expireAbsolute !== null && $expireAbsolute < time()) {

                $this->logout(false);

            } elseif ($this->authTimeout !== null) {

                $session->set($this->authTimeoutParam, time() + $this->authTimeout);

            }

        }


        if ($this->enableAutoLogin) {

            if ($this->getIsGuest()) {

                $this->loginByCookie();

            } elseif ($this->autoRenewCookie) {

                $this->renewIdentityCookie();

            }

        }

    }