参考地址: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. 使用jmeter进行性能测试-Jmeter教程及技巧汇总 (转)

    http://www.jmeter.cf/loadtesting-jmeter.html 为什么使用jmeter, 它免费开源, 不断发展, 功能逐渐强大. 可以做功能,负载, 性能测试.一套脚本可以 ...

  2. Java反射机制详解

    Java反射机制是在运行状态中,对于任意一个类,都能够知道这个类的所有属性和方法:对于任意一个对象,都能够调用它的任意一个方法和属性:这种动态获取的信息以及动态调用对象的方法的功能称为Java语言的反 ...

  3. 【hdu 5918】Sequence I(KMP)

    给定两个数字序列,求a序列中每隔p个构成的p+1个序列中共能匹配多少个b序列. 例如1 1 2 2 3 3 每隔1个的序列有两个1 2 3 kmp,匹配时每次主串往前p个,枚举1到p为起点. 题目 # ...

  4. 【POJ 3041】Asteroids (最小点覆盖)

    每次选择清除一行或者一列上的小行星.最少选择几次. 将行和列抽象成点,第i行为节点i+n,第j列为节点j,每个行星则是一条边,连接了所在的行列. 于是问题转化成最小点覆盖.二分图的最小点覆盖==最大匹 ...

  5. camerc文件播放

    下载CamtasiaStudio 5中文版,打开CamtasiaStudio.exe在左边有生成选项,点左边工具框内添加/导入媒体,则选择下面的批量生成.弹出添加文件的菜单点添加文件,加入你要转换的c ...

  6. 80.Android之内存管理

    转载:http://www.jianshu.com/p/9fb0a795da93 1. Android中的内存 1.1 Android中的垃圾回收机制 Android 平台最吸引开发者的一个特性:有垃 ...

  7. Servlet与JSP版本历史以及Tomcat支持的版本

    查询这个的关键字:Java EE的版本历史. JavaServer Pages (JSP) Java Servlet 参考: https://en.wikipedia.org/wiki/Java_EE ...

  8. IRC(Internet Relay Chat Protocol) Protocal Learning && IRC Bot

    catalogue . Abstract . INTRODUCTION . 通信协议Connection Registration Action . 通信协议Channel operations Ac ...

  9. Linux Hackers/Suspicious Account Detection

    catalog . Linux黑客帐号攻击向量 . Linux可疑帐号检测模型 1. Linux黑客帐号攻击向量 0x1: 将黑客帐号添加到"root"组 . useradd ha ...

  10. string字符串的一系列操作

    IndexOf() 查找字串中指定字符或字串首次出现的位置,返首索引值,如: str1.IndexOf("字"): //查找“字”在str1中的索引值(位置) str1.Index ...