Yii2 自动登录不起作用

Yii2 autologin doesn't work

我尝试在yii2中实现自动登录功能

所以我在配置中启用了自动登录:

'user' => [
    'identityClass' => 'app\models\User',
    'enableAutoLogin' => true,
    'loginUrl' => ['account/login', 'account', 'account/index'],
],

我还在表单配置中添加了 rememberMe 字段

public function scenarios() {
    return [
        'login' => ['username','password','rememberMe'],
        'activate' => ['password','passwordrepeat'],
        'register' => ['username', 'mail'],
        'setup' => ['username', 'password', 'passwordrepeat', 'mail', 'secretkey'],
    ];
}
// ...
[
    ['rememberMe'], 
    'boolean',
    'on' => 'login',
],

我现在在登录时使用它:

public function login() {
    //var_dump((bool) ($this->rememberMe)); exit();
    if (!$this->validate()) {
        return false;
    }

    return Yii::$app->user->login($this->getUser(), (bool) ($this->rememberMe) ? 3600*24*30 : 0);
}

如果我登录,将调用用户函数 getAuthKey 函数并生成一个新的 auth_key。

public function generateAuthKey() {
    $this->auth_key = Yii::$app->getSecurity()->generateRandomString();
    Helper::save($this);
    // Helper is a database helper which will update some rows like last_modified_at and similar in database
}

/**
 * @inheritdoc
 */
public function getAuthKey()
{
    $this->generateAuthKey();
    return $this->auth_key;
}

但我总是登录,它不会设置一些 cookie 变量。 我的饼干总是

console.write_line(document.cookie)
# => "_lcp=a; _lcp2=a; _lcp3=a"

如果我重新启动浏览器,我就没有登录。 我做错了什么?

Yii 似乎不能正确使用 cookies:

var_dump(Yii::$app->getRequest()->getCookies()); exit();

结果:

object(yii\web\CookieCollection)#67 (2) { ["readOnly"]=> bool(true) ["_cookies":"yii\web\CookieCollection":private]=> array(0) { } } 

如果我通过 $_COOKIE 访问,我的值与 JS 中的值相同。

提前致谢

可能是你的自动登录超时没有设置 检查您是否对分配给变量的值进行了正确的分配:

$authTimeout; $absoluteAuthTimeout;

See for more

我想您不必每次都在 getAuthKey 方法中生成授权密钥。您的应用程序尝试将数据库值与存储在您的 cookie 中的授权密钥进行比较。只需在用户插入之前生成一次:

/**
 * @inheritdoc
 */
public function getAuthKey()
{
    return $this->auth_key;
}

/**
 * @inheritdoc
 */
public function beforeSave($insert)
{
    if (!parent::beforeSave($insert)) {
        return false;
    }
    if ($insert) {
        $this->generateAuthKey();
    }
    return true;
}