简介

yii2的自动登录的原理很简单。主要就是利用cookie来实现的,在第一次登录的时候,如果登录成功并且选中了下次自动登录,那么就会把用户的认证信息保存到cookie中,cookie的有效期为1年或者几个月。在下次登录的时候先判断cookie中是否存储了用户的信息,如果有则用cookie中存储的用户信息来登录,

配置

首先在打开yii2配置文件的components中设置user组件

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

只有在enableAutoLogin为true的情况下,如果选择了下次自动登录,那么就会把用户信息存储起来放到cookie中并设置cookie的有效期为3600*24*30秒,以用于下次登录

解析

现在我们来看看Yii中是怎样实现的。

一、第一次登录存cookie

1、login 登录功能

public function login($identity, $duration = 0)
{if ($this->beforeLogin($identity, false, $duration)) {$this->switchIdentity($identity, $duration);$id = $identity->getId();$ip = Yii::$app->getRequest()->getUserIP();Yii::info("User '$id' logged in from $ip with duration $duration.", __METHOD__);$this->afterLogin($identity, false, $duration);}return !$this->getIsGuest();
}

在这里,就是简单的登录,然后执行switchIdentity方法,设置认证信息。

2、switchIdentity设置认证信息

public function switchIdentity($identity, $duration = 0)
{$session = Yii::$app->getSession();if (!YII_ENV_TEST) {$session->regenerateID(true);}$this->setIdentity($identity);$session->remove($this->idParam);$session->remove($this->authTimeoutParam);if ($identity instanceof IdentityInterface) {$session->set($this->idParam, $identity->getId());if ($this->authTimeout !== null) {$session->set($this->authTimeoutParam, time() + $this->authTimeout);}if ($duration > 0 && $this->enableAutoLogin) {$this->sendIdentityCookie($identity, $duration);}} elseif ($this->enableAutoLogin) {Yii::$app->getResponse()->getCookies()->remove(new Cookie($this->identityCookie));}
}

这个方法比较重要,在退出的时候也需要调用这个方法。

这个方法主要有三个功能

1.设置session的有效期

2.如果cookie的有效期大于0并且允许自动登录,那么就把用户的认证信息保存到cookie中

3.如果允许自动登录,删除cookie信息。这个是用于退出的时候调用的。退出的时候传递进来的$identity为null

protected function sendIdentityCookie($identity, $duration)
{$cookie = new Cookie($this->identityCookie);$cookie->value = json_encode([$identity->getId(),$identity->getAuthKey(),$duration,]);$cookie->expire = time() + $duration;Yii::$app->getResponse()->getCookies()->add($cookie);
}

存储在cookie中的用户信息包含有三个值:

$identity->getId()

$identity->getAuthKey()

$duration

getId()和getAuthKey()是在IdentityInterface接口中的。我们也知道在设置User组件的时候,这个User Model是必须要实现IdentityInterface接口的。所以,可以在User Model中得到前两个值,第三值就是cookie的有效期。

二、自动从cookie登录

从上面我们知道用户的认证信息已经存储到cookie中了,那么下次的时候直接从cookie里面取信息然后设置就可以了。

1、AccessControl用户访问控制

Yii提供了AccessControl来判断用户是否登录,有了这个就不需要在每一个action里面再判断了

public function behaviors()
{return ['access' => ['class' => AccessControl::className(),'only' => ['logout'],'rules' => [['actions' => ['logout'],'allow' => true,'roles' => ['@'],],],],];
}

2、getIsGuest、getIdentity判断是否认证用户

isGuest是自动登录过程中最重要的属性。

在上面的AccessControl访问控制里面通过IsGuest属性来判断是否是认证用户,然后在getIsGuest方法里面是调用getIdentity来获取用户信息,如果不为空就说明是认证用户,否则就是游客(未登录)。

public function getIsGuest($checkSession = true)
{return $this->getIdentity($checkSession) === null;
}
public function getIdentity($checkSession = true)
{if ($this->_identity === false) {if ($checkSession) {$this->renewAuthStatus();} else {return null;}}return $this->_identity;
}

3、renewAuthStatus 重新生成用户认证信息

protected function renewAuthStatus()
{$session = Yii::$app->getSession();$id = $session->getHasSessionId() || $session->getIsActive() ? $session->get($this->idParam) : null;if ($id === null) {$identity = null;} else {/** @var IdentityInterface $class */$class = $this->identityClass;$identity = $class::findIdentity($id);}$this->setIdentity($identity);if ($this->authTimeout !== null && $identity !== null) {$expire = $session->get($this->authTimeoutParam);if ($expire !== null && $expire < time()) {$this->logout(false);} else {$session->set($this->authTimeoutParam, time() + $this->authTimeout);}}if ($this->enableAutoLogin) {if ($this->getIsGuest()) {$this->loginByCookie();} elseif ($this->autoRenewCookie) {$this->renewIdentityCookie();}}
}

这一部分先通过session来判断用户,因为用户登录后就已经存在于session中了。然后再判断如果是自动登录,那么就通过cookie信息来登录。

4、通过保存的Cookie信息来登录 loginByCookie

protected function loginByCookie()
{$name = $this->identityCookie['name'];$value = Yii::$app->getRequest()->getCookies()->getValue($name);if ($value !== null) {$data = json_decode($value, true);if (count($data) === 3 && isset($data[0], $data[1], $data[2])) {list ($id, $authKey, $duration) = $data;/** @var IdentityInterface $class */$class = $this->identityClass;$identity = $class::findIdentity($id);if ($identity !== null && $identity->validateAuthKey($authKey)) {if ($this->beforeLogin($identity, true, $duration)) {$this->switchIdentity($identity, $this->autoRenewCookie ? $duration : 0);$ip = Yii::$app->getRequest()->getUserIP();Yii::info("User '$id' logged in from $ip via cookie.", __METHOD__);$this->afterLogin($identity, true, $duration);}} elseif ($identity !== null) {Yii::warning("Invalid auth key attempted for user '$id': $authKey", __METHOD__);}}}
}

先读取cookie值,然后$data = json_decode($value, true);反序列化为数组。

这个从上面的代码可以知道要想实现自动登录,这三个值都必须有值。另外,在User Model中还必须要实现findIdentity、validateAuthKey这两个方法。

登录完成后,还可以再重新设置cookie的有效期,这样便能一起有效下去了。

 $this->switchIdentity($identity, $this->autoRenewCookie ? $duration : 0);

三、退出 logout

public function logout($destroySession = true)
{$identity = $this->getIdentity();if ($identity !== null && $this->beforeLogout($identity)) {$this->switchIdentity(null);$id = $identity->getId();$ip = Yii::$app->getRequest()->getUserIP();Yii::info("User '$id' logged out from $ip.", __METHOD__);if ($destroySession) {Yii::$app->getSession()->destroy();}$this->afterLogout($identity);}return $this->getIsGuest();
}
public function switchIdentity($identity, $duration = 0)
{$session = Yii::$app->getSession();if (!YII_ENV_TEST) {$session->regenerateID(true);}$this->setIdentity($identity);$session->remove($this->idParam);$session->remove($this->authTimeoutParam);if ($identity instanceof IdentityInterface) {$session->set($this->idParam, $identity->getId());if ($this->authTimeout !== null) {$session->set($this->authTimeoutParam, time() + $this->authTimeout);}if ($duration > 0 && $this->enableAutoLogin) {$this->sendIdentityCookie($identity, $duration);}} elseif ($this->enableAutoLogin) {Yii::$app->getResponse()->getCookies()->remove(new Cookie($this->identityCookie));}
}

退出的时候先把当前的认证设置为null,然后再判断如果是自动登录功能则再删除相关的cookie信息。

yii2教程-登录与自动登录机制解析相关推荐

  1. Winform开发框架之系统重新登录、自动登录实现

    在业务系统的操作过程中,有时候,用户需要切换用户进行重新登录,这种情况有时候是因为一个人管理多个用户账号,希望通过不同的账号登录进行管理不同的资料,另一种情况是酒店的换班操作,另一个人接替前面的人进行 ...

  2. 带你一步一步实现验证码登录和自动登录

    文章目录 1.实现最简单的登录 2.过滤器处理中文乱码 3.编写最简单前端页面 4.编写验证码servlet 5.修改前端页面,添加验证码和自动登录按钮 6.实现自动登录 7.前端脚本编写:读取coo ...

  3. python自动登录教程_Python 实现自动登录+点击+滑动验证功能

    需要用到的库有selenium,还需要安装Chrome浏览器驱动,具体如何安装我就不详述了 在这里我模拟了csdn的登录过程 ** 1**.首先打开网页,用户名+密码登录,然后定位用户名输入框,和密码 ...

  4. linux sshd自动登录,SSH自动登录的几种方法

    1. 自动ssh/scp方法== A为本地主机(即用于控制其他主机的机器) ; B为远程主机(即被控制的机器Server), 假如ip为192.168.60.110; A和B的系统都是Linux 在A ...

  5. Cookie-网站登录-下次自动登录

    做网站前端用户登录时需要有个下次自动登录的功能.看了看各大网站都有这种功能. 问题描述:用户登录网站时,一般有个checkbox让用户选择是否可以下次自动登录.选择后,即使用户关闭浏览器,下次再访问这 ...

  6. C# winform 登录 实现自动登录 和记住密码功能

    登录界面如下 配置文件如下  在App.config下 写个<appSettings>节点  照着我的写就行了 单击登录时 Configuration cfa = Configuratio ...

  7. USTB校园网一键登录开机自动登录

    背景介绍 针对USTB校园网用户,每次开机后经常需要进行如下操作: ① 打开校园网登录页面 ② 手动输入学号和密码 ③ 点击登录按钮 作为一个资深的小懒虫,经过九九八十一天的研发,开发出来一键登录的工 ...

  8. python自动登录教程_Python实现自动登录百度空间的方法,python自动登录

    location.href="/zhouciming/home" rel="external nofollow" ;

  9. 关于新浪微博开放平台微博登录授权后再次登录会自动登录问题的解决办法

    ios和android版本sso登陆和Oauth2.0登录跳转到新浪登录页面后,如果客户端里只有一个帐号,那么就会默认地选择这个帐号授权了,没给用户选择,也无法添加帐号.这种情况只能先去新浪的客户端里 ...

最新文章

  1. python【力扣LeetCode算法题库】10-正则表达式匹配
  2. B-树的插入、查找、删除
  3. 深度学习总结:pytorch构建RNN和LSTM,对比原理图加深理解
  4. 深入理解Java内存模型(七)——总结
  5. 微信公共平台接口开发--Java实现
  6. centos下mysql更改数据存放目录_CentOS下mysql更改数据存放目录 --转载
  7. 友益文书类似软件_网易有道词典笔,让你的英文书也有实时翻译功能
  8. apache kafka源代码工程环境搭建(IDEA)
  9. 测试接口python常用命令_用python实现接口测试(四、操作MySQL)-阿里云开发者社区...
  10. python matplotlib绘图显示中文
  11. matlab meshlab,MeshLab(网格模型处理软件)下载-MeshLab官方版下载[电脑版]-PC下载网
  12. 禁不住诱惑?不可描述的应用之下暗藏巨大风险
  13. 在线文本加密解密工具
  14. linux查看外网IP
  15. HTML学习之制作导航网页
  16. android 查看 屏幕刷新率,屏幕刷新率检查app
  17. 在上海奋斗的五年---从月薪3500到700万 (一个西北真汉子的人生)
  18. ne_products 表
  19. [激光原理与应用-30]:典型激光器 -2- 气体激光器 (连续激光器)
  20. 数模国赛历年题目 1992——2021

热门文章

  1. L学姐北京美团测开一面二面
  2. (转)申请企业级IDP、真机调试、游戏接入GameCenter 指南、游戏接入OpenFeint指南;...
  3. 尝试添加 --skip-broken 来跳过无法安装的软件包 或 --nobest 来不只使用最佳选择的软件包
  4. wamp php不可用_使用wamp扩展php时出现服务未启动的解决方法
  5. 如何查看自己steam库里游戏是哪个区的
  6. repo remote元素中fetch=“.“或者“..“的理解
  7. 【AD21】keepout层和机械1层怎么相互转换
  8. Kafka节点服役和退役
  9. 山西职称英语和计算机考试报名时间,山西2017职称英语报考条件
  10. 【博文】:甲骨文收购AMD的缘由