zoukankan      html  css  js  c++  java
  • yii2 自动登录解读

    今日遇到一个需要将当前用户,全部登出系统(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() 方法我就不再 详细说明了。。。大家自行查看源码

  • 相关阅读:
    公有云数据库服务的申请与使用
    linux集群
    shell基础知识
    LNMP环境配置
    LAMP环境搭建与配置
    12月17日linux学习
    12月16日linux学习(文档的压缩与打包)
    12月13、14号linux学习
    12月12日linux学习
    目录结构
  • 原文地址:https://www.cnblogs.com/zjhblogs/p/8601807.html
Copyright © 2011-2022 走看看