Auto login using “remember me” not working

2020-05-01 06:26发布

I am new to Yii2. I'm using Yii 2 basic template.

I have the "remember me" functionality implemented on my web application, but it is not working as I think it was supposed to. I can successfully log in (with a checked "remember me" checkbox). But after closing the browser and opening the website again I am not logged in, but instead redirected to the login page.

I have set enableAutoLogin to true in the config file

'user' => [
        'identityClass' => 'app\models\User',
        'enableAutoLogin' => true,
         'authTimeout' => 86400,
    ],

4条回答
我欲成王,谁敢阻挡
2楼-- · 2020-05-01 07:00

Using "Remember Me" in the login :

1- Create your identity class using this link : http://www.yiiframework.com/doc-2.0/guide-security-authentication.html

2- Add this line to the config file :

...

'components' => [
    'user' => [
        'enableAutoLogin' => true, /* Whether to enable cookie-based login. */
    ],
], 

...

3- Use this code after you validate login form :

/* If [[enableSession]] is `true`:
- the identity information will be stored in session and be available in the next requests
- in case of `$duration == 0`: as long as the session remains active or till the user closes the browser
- in case of `$duration > 0`: as long as the session remains active or as long as the cookie
  remains valid by it's `$duration` in seconds when [[enableAutoLogin]] is set `true`.
  */
$duration = $this->remember ? (30 * 24 * 3600) : 0;
Yii::$app->user->login($user, $duration);
查看更多
Root(大扎)
3楼-- · 2020-05-01 07:02

1. Do this in your user (if using any other model for login then use that model) model.

add this just before rules

public $rememberMe = true;

and define in your model

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

2. now do this in your view page

 <?= $form->field($model, 'rememberMe')->checkbox(['template' => "<div class=\"col-lg-offset-1 col-lg-3\">{input} {label}</div>\n<div class=\"col-lg-8\">{error}</div>"]) ?>
查看更多
三岁会撩人
4楼-- · 2020-05-01 07:06

Make sure that your user model have implemented yii\web\IdentityInterface and it has the following methods

  1. findIdentity()
  2. findIdentityByAccessToken()
  3. getId()
  4. getAuthKey()
  5. validateAuthKey()

    use yii\db\ActiveRecord;

use yii\web\IdentityInterface;

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

Refer docs for more about auto login

查看更多
倾城 Initia
5楼-- · 2020-05-01 07:19

what i have done is in models:

                if($this->rememberMe == 1){ 
                     setcookie (\Yii::getAlias('@site_title')."_admin_email", $this->username, time()+3600*24*4);
                     setcookie (\Yii::getAlias('@site_title')."_admin_password", $this->password, time()+3600*24*4);
                }else{
                     setcookie (\Yii::getAlias('@site_title')."_admin_email", '');
                     setcookie (\Yii::getAlias('@site_title')."_admin_password", '');
                }

and in view page retrive it using :

$cookies_email = isset($_COOKIE[Yii::getAlias('@site_title')."_admin_email"]) ? $_COOKIE[Yii::getAlias('@site_title')."_admin_email"] : '';?>
<?php $cookies_password = isset($_COOKIE[Yii::getAlias('@site_title')."_admin_password"]) ? $_COOKIE[Yii::getAlias('@site_title')."_admin_password"] : '';?>

and my problem is solved :)

查看更多
登录 后发表回答