我是Yii2的新手。我正在使用Yii 2基本模板。
我在我的web应用程序上实现了"记住我"功能,但它并没有像我想象的那样工作。我可以成功登录(勾选"记得我"复选框)。但在关闭浏览器并再次打开网站后,我没有登录,而是重定向到登录页面。
我在配置文件中将enableAutoLogin
设置为true
'user' => [
'identityClass' => 'appmodelsUser',
'enableAutoLogin' => true,
'authTimeout' => 86400,
],
1.在用户模型中执行此操作(如果使用任何其他模型登录,则使用该模型)。
将其添加到rules
之前
public $rememberMe = true;
并在您的模型中定义
public function login()
{
if ($this->validate()) {
return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600*24*30 : 0);
}
return false;
}
2.现在在您的视图页面中执行此操作
<?= $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>"]) ?>
确保您的用户模型已经实现了yiiwebIdentityInterface
,并且它具有以下方法
- findIdentity()
- findIdentityByAccessToken()
- getId()
- getAuthKey()
-
validateAuthKey()
使用yii\db\ActiveRecord;
使用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;
}
}
有关自动登录的更多信息,请参阅文档
在登录中使用"记住我":
1-使用此链接创建您的身份类:http://www.yiiframework.com/doc-2.0/guide-security-authentication.html
2-将此行添加到配置文件:
'components' => [
'user' => [
'enableAutoLogin' => true, /* Whether to enable cookie-based login. */
],
],
3-验证登录表单后使用此代码:
/* 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);