2016-11-14 23:49:05 9844次浏览 3条回答 4 悬赏 50 金钱

登录方式是不是一共有三种?一种是账号密码,一种是cookie,一种是token。
账号密码登录我能理解,但是cookie登录,YII2具体是怎么实现的呢?
我大概步骤是能了解,就是把弄个认证类,然后认证类里就写getAuthKey()validateAuthKey($authKey),然后就能实现自动登录?那cookie的时间怎么设置的呀?。。。。。。我很懵逼呀,求大神帮忙,给我一个连接,我自己去看也成,我实在找不到了。最好是连认证,授权一起给我讲一下,或者给我丢个连接,我自己看,文档我看了N遍了,过程我能理解,就是不知道具体实现。

最佳答案

  • javalzbin 发布于 2016-11-15 11:02 举报

    先说自动登录,cookie在哪里设置的,允许自动登录必须得启用enableAutoLogin,设置为true

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

    然后看登录,在你的LoginFrom中的login方法有这么一行代码:

    return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
    

    也是真正执行登录操作的代码,他实际上调用的是\yii\web\User的login方法,这个类的实际路径在:盘符/项目名/vendor/yiisoft/yii2/web/User.php

    public function login(IdentityInterface $identity, $duration = 0)
    {
    	if ($this->beforeLogin($identity, false, $duration)) {
    		$this->switchIdentity($identity, $duration);
                    ............
    		...其他代码..
    		...........
    	}
    	......
    }
    

    首先执行登录之前的操作,然后,关键是$this->switchIdentity($identity, $duration)这个方法:

    public function switchIdentity($identity, $duration = 0)
    {
    	......
        ......
    	if ($identity) {
    		......
    		......
    		if ($duration > 0 && $this->enableAutoLogin) {
    			$this->sendIdentityCookie($identity, $duration);
    		}
    	} elseif ($this->enableAutoLogin) {
    		......
    	}
    }
    

    在$this->sendIdentityCookie($identity, $duration);这里把cookie设置进去

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

    Yii::$app->getResponse()->getCookies()->add($cookie); 这里设置cookie

    到这里,应该解决了cookie的设置的问题了吧。

    然后说说自动登录的实现
    在SiteController中的actionLogin()方法,他判断这个用户是不是登录用户,如果不是,则返回主页或者说登录页

    if (!\Yii::$app->user->isGuest) {
                return $this->goHome();
    }
    

    还是走到\yii\web\User这个类,调用了getIsGuest()方法,getIsGuest()方法调用getIdentity($autoRenew = true)方法

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

    是否开启自动登录($this->enableSession && $autoRenew),是,那么执行renewAuthStatus()方法:

    protected function renewAuthStatus()
    {
    	......
    	...前面代码是session有值的判断,不看他...
    	......
    
    	if ($this->enableAutoLogin) {
    		if ($this->getIsGuest()) {
    			$this->loginByCookie();
    		} elseif ($this->autoRenewCookie) {
    			$this->renewIdentityCookie();
    		}
    	}
    }
    

    启用自动登录$this->enableAutoLogin为true,然后判断是否是访客$this->getIsGuest(),如果是,则执行登录,从cookie登录$this->loginByCookie();这就是cookie登录的具体实现

    protected function loginByCookie()
        {
    		//cookie取值
            $value = Yii::$app->getRequest()->getCookies()->getValue($this->identityCookie['name']);
            if ($value === null) {
                return;
            }
    
            $data = json_decode($value, true);
            if (count($data) !== 3 || !isset($data[0], $data[1], $data[2])) {
                return;
            }
    
            list ($id, $authKey, $duration) = $data;
            /* @var $class IdentityInterface */
            $class = $this->identityClass;
            $identity = $class::findIdentity($id);
            if ($identity === null) {
                return;
            } elseif (!$identity instanceof IdentityInterface) {
                throw new InvalidValueException("$class::findIdentity() must return an object implementing IdentityInterface.");
            }
    
            if ($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);
                }
            } else {
                Yii::warning("Invalid auth key attempted for user '$id': $authKey", __METHOD__);
            }
        }
    

    $identity = $class::findIdentity($id);//根据cookie保存的记录id在数据库中找,这里调用的是在配置文件中main.php配置的

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

    common\models\User这个类的findIdentity($id)方法

    public static function findIdentity($id)
        {
            return static::findOne(['id' => $id, 'status' => self::STATUS_ACTIVE]);
        }
    

    if ($identity->validateAuthKey($authKey)) {} 则调用 common\models\User这个类的validateAuthKey($authKey)方法,实际上就是判断这个记录id的auth_key这个数据库的值是否跟保存到cookie中的一样,如果一样,返回true。
    目的是,所以,如果管理员要修改一个帐号的密码,实际上出了修改他的密码password_hash之外,还需要修改auth_key,否则他如果以前登录过。cookie有值,一样可以正常登录。这点很重要

    然后就没啥好说的拉,就是正常的登录流程拉,个人建议,好好利用ide的debug功能,跟踪代码绝对杠杠的

    7 条回复
    回复于 2016-11-15 13:16 回复

    也就是说authkey不是用来判断登录的,而是判断密码是否修改的意思?

    回复于 2016-11-15 15:29 回复

    不是这个意思,cookie除了保存记录的id值,还有保存authkey,那么通过cookie登录时,通过cookie取的记录的id
    值,然后匹配cookie中的authkey是否和数据库查询出来的authkey相当,如果相等,就能自动登录,否则登录失败

    回复于 2016-11-15 16:04 回复

    我大概明白了,我再测试几次应该就能弄明白,现在就是自动验证登录这地方不知道怎么做呢

    回复于 2016-11-15 16:07 回复

    你想做什么?自动登录不用你去改,你只需要在执行action之前,通过这句代码 if (!\Yii::$app->user->isGuest) {} 他就自动帮你做了,如果条件为true,表示没有登录,你就跳转到登录页面,如果为false,他就是已经登录的用户

    回复于 2016-11-15 16:08 回复

    cookie登录,用户每次进入页面都要if一次?

    回复于 2016-11-15 16:17 回复

    session没有值,cookie有值,它会验证cookie的值,然后,他会把值放到session中去,下次他会从session中取值来判断,我建议你写一个父类,让你的Controller都继承这个父类,然后你在父类中重写beforeAction($action)方法,在这里去判断就好了,判断通过,beforeAction方法返回true,然后他自动会去执行你要执行的Controller的action,你需要在一个地方写一句代码,就可以拦截所有为登录和已经登录的请求了

    回复于 2016-11-15 16:19 回复

    你还是debug跟踪一下代码吧,我表达的并没有看代码直接

    觉得很赞
  • 回答于 2016-11-15 10:06 举报

    完整的具体实现在高级版脚手架那块。
    按照你所理解的登录,是两种。token是验证 API 授权才需要用到的。
    你可以参考这个连接http://www.yiichina.com/tutorial/965,它拥有无比完整的代码。然后把登录流程看一遍(在vendor目录下的代码可以不用看),再结合权威指南的安全-》认证那块。你上述的所有问题必定都可以在这两块得到解决。

    6 条回复
    回复于 2016-11-15 10:37 回复

    。。。那么简单的登录我早就会了,而且那连接里啥都没有啊

    回复于 2016-11-15 14:09 回复

    唉,你忽略了太多太多了呀。还有什么东西比官方高级版的脚手架对YII的user组件登录功能还要深刻了解的吗?我没有给你任何代码,因为在它面前我真没资格呀。我只是给你提示一条指向它的路。让你去了解它呀。

    回复于 2016-11-15 14:46 回复

    正常登录OK,COOKIE自动登录就很麻烦,一,用户登录过一次,而且点过“记住我”,这时候cookie里保存的是什么?如果这个cookie被别人知道了,别人能用这个cookie来登录吗,如果用户在别的地方登录,那是不是要更新数据库里的authkey字段的值,让之前的cookie失效,如果我自己做这些我也都能做出来,但是YII2自己有,我就想知道如何根据YII2自带的登录机制去完成这些。

    回复于 2016-11-15 15:47 回复

    YII登录用到的cookie存的是 ID,authkey,以及还剩多久失效。别人几乎不可能知道这个cookie,因为YII的yii\web\Cookie::httpOnly 为 true,这点权威指南有提及。如果用户在别的地方登录,这并不应该影响之前的登录。我就是下班回到家而已,无需这么敏感。如果你实在对安全有兴趣,要么寄希望于用户的浏览器是最新chrome和chrome的BUG,要么抛弃cookie。另外,你应该坚信YII框架。

    回复于 2016-11-15 16:03 回复

    用户第一次登陆,然后把浏览器关掉,然后再打开浏览器,进入我的网站,登陆状态直接就应该是登录的吧?那是每次都要验证一次吗?还是?

    回复于 2016-11-15 18:47 回复

    关闭浏览器之后,你便失去你本次登录的唯一凭证,session。于是需要再次执行登录操作。但是因为你自动登录的cookie的存在。所以你没有看到登录页面,但实际上已经进行了登录。

  • 回答于 2016-11-15 14:46 举报

    common/models/LoginForm.php里面

    public function validatePassword($attribute, $params)
          {
            if (!$this->hasErrors()) {
                $user = $this->getUser();
                //validatePassword验证登录密码
                if (!$user || !$user->validatePassword($this->password)) {
                    $this->addError($attribute, "wrong");
                }
           }
        }
    
您需要登录后才可以回答。登录 | 立即注册
数字派
总监

数字派 北京

注册时间:2016-04-19
最后登录:2023-03-07
在线时长:52小时34分
  • 粉丝10
  • 金钱1515
  • 威望10
  • 积分2135

热门问题