Yii2 autologin doesn't work

佐手、 提交于 2019-12-13 23:23:39

问题


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'],
],

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);
}

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;
}

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?

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

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

Results in:

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

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

Thanks in advance


回答1:


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;
}



回答2:


Could be your timeout for autologin is not set Check if you have a proper assignment to the value assigned to the variable:

$authTimeout; $absoluteAuthTimeout;

See for more



来源:https://stackoverflow.com/questions/30556419/yii2-autologin-doesnt-work

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!