参考地址:http://www.kuitao8.com/20150518/3747.shtml

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

在下次登录的时候先判断cookie中是否存储了用户的信息,如果有则用cookie中存储的用户信息来登录,

配置User组件

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

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

我们看到enableAutoLogin就是用来判断是否要启用自动登录功能,这个和界面上的下次自动登录无关。
只有在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));
        }
    }

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

这个方法主要有三个功能

  • 设置session的有效期
  • 如果cookie的有效期大于0并且允许自动登录,那么就把用户的认证信息保存到cookie中
  • 如果允许自动登录,删除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.0自动登录功能的实现方法的更多相关文章

  1. 自己Cookie写的自动登录功能 包含BASE64 和MD5的使用

    sql表 username  password字段 User类 有 id username password等字段 Service有一函数 @Override public User findUser ...

  2. 二十 Filter&自动登录功能

    Filter过滤器 过滤器,其实就是对客户端发出来的请求进行过滤,浏览器发出,然后服务器用Servelt处理.在中间就可以过滤,起到的是拦截的作用. 不仅仅作用于客户端请求,而且过滤服务器响应 作用: ...

  3. Vue+Vuex 实现自动登录功能

    刚刚实现了Vue+Vuex的自动登录功能,在实现的时候遇到了一些问题,这里记录一下: 因为这个还不够完善,在写完下列代码后,又进行了补充,可以从https://www.cnblogs.com/xiao ...

  4. ThinkPHP登录功能的实现方法

    登陆功能是PHP程序设计中常见的功能.本文ThinkPHP实例主要完成注册成功后进入首页,并告诉你是登录用户的功能.具体实现步骤如下: 第一步:在config.php文件中加上: 完整实现代码如下: ...

  5. spring security实现记住我下次自动登录功能

    目录 spring security实现记住我下次自动登录功能 一.原理分析 二.实现方式 2.1 简单实现方式 2.2 数据库实现方式 三.区分是密码登录还是rememberme登录 spring ...

  6. cookie理解与实践【实现简单登录以及自动登录功能】

    cookie理解 Cookie是由W3C组织提出,最早由netscape社区发展的一种机制 http是无状态协议.当某次连接中数据提交完,连接会关闭,再次访问时,浏览器与服务器需要重新建立新的连接: ...

  7. CDLinux 自动休眠功能的关闭方法

    CDLinux 自动休眠功能的关闭方法: 控制台下使用xset命令来完成. xset q  可以查看当前屏幕保护和电源管理的状态信息 具体设置时,常用的有以下参数: xset s  //这个参数设置屏 ...

  8. mate桌面用户 root 自动登录lightdm.conf -20190520 方法【fedora 21】mate

    桌面用户自动登录lightdm.conf -20190520 方法修改 /etc/lightdm/lightdm.conf 步骤:1 vim  /etc/lightdm/lightdm.conf 解除 ...

  9. yii2.0用户登录,退出判断(摘录)

    文章来源:http://blog.sina.com.cn/s/blog_88a65c1b0101ix13.html 判断用户是否登录 在 Yii2.0 里面,判断用户是否已经登录,我们用下面的代码即可 ...

随机推荐

  1. java-URLConnection网络数据收取

    通过url创建connection方式收取 import java.io.BufferedReader; import java.io.ByteArrayOutputStream; import ja ...

  2. lift and throw

    import java.util.*; import java.math.*; public class Main { public static void main(String[] args) { ...

  3. 【faster-rcnn】训练自己的数据集时的坑

    既然faster-rcnn原版发表时候是matlab版代码,那就用matlab版代码吧!不过遇到的坑挺多的,不知道python版会不会好一点. ======= update ========= 总体上 ...

  4. 【BZOJ-3437】小P的牧场 DP + 斜率优化

    3437: 小P的牧场 Time Limit: 10 Sec  Memory Limit: 128 MBSubmit: 705  Solved: 404[Submit][Status][Discuss ...

  5. bootstrap 双层模态框的实现

    <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8&quo ...

  6. UOJ262 【NOIP2016】换教室

    本文版权归ljh2000和博客园共有,欢迎转载,但须保留此声明,并给出原文链接,谢谢合作. 本文作者:ljh2000作者博客:http://www.cnblogs.com/ljh2000-jump/转 ...

  7. Microsoft SQL Server,错误: 229 解决方案

    今天我在数据库新建一个用户时,碰到了一个奇怪的问题,账号建好了,也指定了该账号上对应的数据库.但是,奇怪的问题出现了,死活不让我新建表,提示如下: 最后,给我找到问题所在了,就是在指定表权限的时候权限 ...

  8. String、StringBuffer、StringBuilder源码分析

    利用反编译具体看看"+"的过程 1 public class Test 2 { 3 public static void main(String[] args) 4 { 5 int ...

  9. 加州大学伯克利分校Stat2.2x Probability 概率初步学习笔记: Section 5 The accuracy of simple random samples

    Stat2.2x Probability(概率)课程由加州大学伯克利分校(University of California, Berkeley)于2014年在edX平台讲授. PDF笔记下载(Acad ...

  10. 高性能JavaScript(您值得一看)

    众所周知浏览器是使用单进程处理UI更新和JavaScript运行等多个任务的,而同一时间只能有一个任务被执行,如此说来,JavaScript运行了多长时间就意味着用户得等待浏览器响应需要花多久时间. ...