Yii2自动登录不起作用 [英] Yii2 autologin doesn't work

查看:1838
本文介绍了Yii2自动登录不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I try to realize the autologin feature in yii2.

所以我启用自动登录的配置:

So I've enabled autologin in configuration:

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

在表单配置此外,我已经添加了rememberMe领域

Also I've added rememberMe field in form configuration

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

我现在用的这个登录时:

I'm using this now at 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。

If I log in, users function getAuthKey function is called and a new auth_key is generated.

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变量。
我的饼干总是

But always, I log in, it doesn't set some cookie variables. My cookies are always

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

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

And if I restart my browser I'm not logged in. What am I doing wrong?

似乎Yii的不正常工作的cookie:

It seems that Yii doesn't work with cookies correctly:

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。

If I access via $_COOKIE I have the same values as in JS.

在此先感谢

推荐答案

我猜你没有产生在你的getAuthKey方法权威性键每次。您的应用程序试图数据库值与存储在您的Cookie的身份验证密钥。只是生成它的用户插入前一次:

I guess you don't have to generate auth key every time in your getAuthKey method. Your app tries to compare database value to the auth key stored in your cookie. Just generate it once before user insert:

/**
 * @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;
}

这篇关于Yii2自动登录不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆