码迷,mamicode.com
首页 > 其他好文 > 详细

yii2 自动登录解读

时间:2018-03-19 14:57:46      阅读:215      评论:0      收藏:0      [点我收藏+]

标签:更新   cte   在线   class   status   idp   guest   style   func   

今日遇到一个需要将当前用户,全部登出系统(YII2框架制作)重新登录的需求

仔细回忆一遍,Yii2的登录流程,竟然有些不太明白,于是下午空闲时 重新看了下Yii2的用户登录源码

 

文件位于YII2项目下:vender/yiisoft/yii2/web/User.php

    /**
     * @身份属性类对象 是一个 实现IdentityInterface接口的一个对象
     */
    public $identityClass;
    /**
     * @var bool 属性 是否使用(cookie)自动登录
     */
    public $enableAutoLogin = false;
    /**
     * @var bool 属性 是否启用Session,如果为false 则这个应用意味着无状态
   * 如 RESTful api
*/ public $enableSession = true;

1.首先需要开发web端用于 一般都会启用Session(会话控制) 

public $enableSession = true;

2.自动登录有2种情况 (1.session 会话保持,2.cookie 自动登录)

    protected function renewAuthStatus()
    {
        //获取用户信息 session
        $session = Yii::$app->getSession();
        $id = $session->getHasSessionId() || $session->getIsActive() ? $session->get($this->idParam) : null;
        
        if ($id === null) {
            $identity = null;
        } else {
            /* @var $class IdentityInterface */
            $class = $this->identityClass;
            $identity = $class::findIdentity($id);
        }
        //如果在session找到用户信息 载入到身份模型
        $this->setIdentity($identity);
        //如果没有在session 中找到模型 且自动登录时间没有过期
        if ($identity !== null && ($this->authTimeout !== null || $this->absoluteAuthTimeout !== null)) {
            $expire = $this->authTimeout !== null ? $session->get($this->authTimeoutParam) : null;
            $expireAbsolute = $this->absoluteAuthTimeout !== null ? $session->get($this->absoluteAuthTimeoutParam) : null;
            if ($expire !== null && $expire < time() || $expireAbsolute !== null && $expireAbsolute < time()) {
                //如果自动登录时间过期 则注销信息
                $this->logout(false);
            } elseif ($this->authTimeout !== null) {
                //否则如果记录了 最长在线时间 重置最长在线时间
                $session->set($this->authTimeoutParam, time() + $this->authTimeout);
            }
        }
        //确认启用了登录,则尝试使用cookie登录
        if ($this->enableAutoLogin) {
            if ($this->getIsGuest()) {
                //使用cokie登录
                $this->loginByCookie();
            } elseif ($this->autoRenewCookie) {
                //更新cookie信息 主要是时间更新
                $this->renewIdentityCookie();
            }
        }
    }

 

下面关于 loginByCookie() 方法我就不再 详细说明了。。。大家自行查看源码

 

yii2 自动登录解读

标签:更新   cte   在线   class   status   idp   guest   style   func   

原文地址:https://www.cnblogs.com/zjhblogs/p/8601807.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!