Yii2 用户在短时间内退出,而会话超时设置为 30 天



Yii2 用户在短时间内被注销,而他们仍应登录 30 天。

我使用的是 PHP 5.6、AWS Elastic Beanstalk 和缓存会话,我也在具有数据库会话和文件会话的单个 EC2 服务器上尝试了相同的代码,但它没有解决问题。

我不知道这一点是否有帮助,当我登录 Firefox 浏览器然后关闭它,然后重新打开它以注销用户身份打开的网站时,我在 chrome 上尝试了同样的情况,它让我保持登录用户。

我已经包含了代码的相关部分:

配置

'components' => [
...
'session' => [
        'class' => 'yiiwebCacheSession',
    ],
    'user' => [
        'identityClass' => 'appmodelsUser',
        'enableSession' => true,
        'autoRenewCookie' => true,
        'authTimeout' => 657567576,
    ],
...
]

登录操作

public function actionLogin()
{
    $model = new LoginForm();
    if ($model->load(Yii::$app->request->post()) && $model->login()) {
        return $this->goBack();
    } else {
        return $this->render('login', [
            'model' => $model,
        ]);
    }
}

登录自

public function login()
{
    if ($this->validate()) {
        return Yii::$app->user->login($this->getUser(), 3600 * 24 * 30);
    } else {
        return false;
    }
}

您需要基于 cookie 的登录。

为此,首先必须在组件中启用enableAutoLogin参数user

因此需要在用户表中有一个auth_key字段。 并覆盖getAuthKeyvalidateAuthKey和某些函数。 像这样的代码:

<?php
use yiidbActiveRecord;
use yiiwebIdentityInterface;
class User extends ActiveRecord implements IdentityInterface
{
    public static function tableName()
    {
        return 'user';
    }
    /**
     * Finds an identity by the given ID.
     *
     * @param string|integer $id the ID to be looked for
     * @return IdentityInterface|null the identity object that matches the given ID.
     */
    public static function findIdentity($id)
    {
        return static::findOne($id);
    }
    /**
     * Finds an identity by the given token.
     *
     * @param string $token the token to be looked for
     * @return IdentityInterface|null the identity object that matches the given token.
     */
    public static function findIdentityByAccessToken($token, $type = null)
    {
        return static::findOne(['access_token' => $token]);
    }
    /**
     * @return int|string current user ID
     */
    public function getId()
    {
        return $this->id;
    }
    /**
     * @return string current user auth key
     */
    public function getAuthKey()
    {
        return $this->auth_key;
    }
    /**
     * @param string $authKey
     * @return boolean if auth key is valid for current user
     */
    public function validateAuthKey($authKey)
    {
        return $this->getAuthKey() === $authKey;
    }
}

对于为每个用户生成新auth_key

class User extends ActiveRecord implements IdentityInterface
{
    ......
    public function beforeSave($insert)
    {
        if (parent::beforeSave($insert)) {
            if ($this->isNewRecord) {
                $this->auth_key = Yii::$app->security->generateRandomString();
            }
            return true;
        }
        return false;
    }
}

我建议您阅读本文的所有详细信息:
http://www.yiiframework.com/doc-2.0/guide-security-authentication.html

最新更新