在Yii2中禁用会话重新生成

时间:2015-01-29 13:45:49

标签: session cookies yii2

我有一个Yii2应用程序,它通过外部API完成大部分工作,包括身份验证和大多数读取/更新请求。

登录后,我在会话中存储了一些加密值,并将加密密钥存储在cookie中。

问题是,cookie(或会话?)..在不活动30分钟后过期..但会话自动重新生成(不提示用户登录), 但是价值的检索被打破了。

主要问题是它很难重现(如果你让页面打开过夜通常会发生这种情况。)

我已将记住我 Cookie过期时间设置为 0 但似乎有更多的选择需要解决。

以下是存储/检索会话数据的函数。

public static function storeData($stored_data)
    {
        $security = Yii::$app->getSecurity();
        $key = $security->generateRandomKey();
        $encrypted = $security->encryptByKey($stored_data, $key);

        Yii::$app->getSession()->set('stored_data', $encrypted);
        Yii::$app->response->cookies->add(new Cookie([
            'name' => 'key',
            'value' => $key,
            //'expire' => time() + 60*60*24*30, 
        ]));
    }


    private static function getData()
    {
        $security = Yii::$app->getSecurity();
        $encrypted = Yii::$app->getSession()->get('stored_data');
        $key = Yii::$app->request->cookies->get('key');

        $stored_data= $security->decryptByKey($encrypted, $key);

        return $stored_data;
    }

1 个答案:

答案 0 :(得分:0)

使用此Cookie生成代码而不是

public static function storeData($stored_data)
{
    $security = Yii::$app->getSecurity();
    $key = $security->generateRandomKey();
    $encrypted = $security->encryptByKey($stored_data, $key);

    Yii::$app->getSession()->set('stored_data', $encrypted);
    $cookie = new CHttpCookie([
        'name' => 'key',
        'value' => $key,
    ]);
    $cookie->expire = time()+60*60*24*180; 
    Yii::app()->request->cookies['key'] = $cookie;
    Yii::$app->response->cookies->add(Yii::app()->request->cookies['key']);
}

在你的config / main.php里面

return array(
    'components'=>array(
        'request'=>array(
            'enableCookieValidation'=>true,
        ),
    ),
);

获取更多详情here

相关问题