当前位置:首页 > CMS教程 > 其它CMS > 列表

Yii2框架实现登录、退出及自动登录功能的方法详解

发布:smiling 来源: PHP粉丝网  添加日期:2021-08-16 10:25:24 浏览: 评论:0 

这篇文章主要介绍了Yii2框架实现登录、退出及自动登录功能的方法,结合实例形式详细分析了Yii2框架实现登录、退出及自动登录功能的原理、实现方法与相关操作注意事项,需要的朋友可以参考下。

本文实例讲述了Yii2框架实现登录、退出及自动登录功能的方法,分享给大家供大家参考,具体如下:

自动登录的原理很简单。主要就是利用cookie来实现的

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

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

配置User组件

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

  1. 'user' => [ 
  2.  'identityClass' => 'app\models\User'
  3.  'enableAutoLogin' => true, 
  4. ], 

我们看到enableAutoLogin就是用来判断是否要启用自动登录功能,这个和界面上的下次自动登录无关。

只有在enableAutoLogin为true的情况下,如果选择了下次自动登录,那么就会把用户信息存储起来放到cookie中并设置cookie的有效期为3600*24*30秒,以用于下次登录

现在我们来看看Yii中是怎样实现的。

一、第一次登录存cookie

1、login 登录功能

  1. public function login($identity$duration = 0) 
  2.   if ($this->beforeLogin($identity, false, $duration)) { 
  3.    $this->switchIdentity($identity$duration); 
  4.    $id = $identity->getId(); 
  5.    $ip = Yii::$app->getRequest()->getUserIP(); 
  6.    Yii::info("User '$id' logged in from $ip with duration $duration."__METHOD__); 
  7.    $this->afterLogin($identity, false, $duration); 
  8.   } 
  9.   return !$this->getIsGuest(); 

在这里,就是简单的登录,然后执行switchIdentity方法,设置认证信息。

2、switchIdentity设置认证信息

  1. public function switchIdentity($identity$duration = 0) 
  2.   $session = Yii::$app->getSession(); 
  3.   if (!YII_ENV_TEST) { 
  4.    $session->regenerateID(true); 
  5.   } 
  6.   $this->setIdentity($identity); 
  7.   $session->remove($this->idParam); 
  8.   $session->remove($this->authTimeoutParam); 
  9.   if ($identity instanceof IdentityInterface) { 
  10.    $session->set($this->idParam, $identity->getId()); 
  11.    if ($this->authTimeout !== null) { 
  12.     $session->set($this->authTimeoutParam, time() + $this->authTimeout); 
  13.    } 
  14.    if ($duration > 0 && $this->enableAutoLogin) { 
  15.     $this->sendIdentityCookie($identity$duration); 
  16.    } 
  17.   } elseif ($this->enableAutoLogin) { 
  18.    Yii::$app->getResponse()->getCookies()->remove(new Cookie($this->identityCookie)); 
  19.   } 

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

这个方法主要有三个功能

① 设置session的有效期

② 如果cookie的有效期大于0并且允许自动登录,那么就把用户的认证信息保存到cookie中

③ 如果允许自动登录,删除cookie信息。这个是用于退出的时候调用的。退出的时候传递进来的$identity为null

  1. protected function sendIdentityCookie($identity$duration
  2.   $cookie = new Cookie($this->identityCookie); 
  3.   $cookie->value = json_encode([ 
  4.    $identity->getId(), 
  5.    $identity->getAuthKey(), 
  6.    $duration
  7.   ]); 
  8.   $cookie->expire = time() + $duration
  9.   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里面再判断了

  1. public function behaviors() 
  2.   return [ 
  3.    'access' => [ 
  4.     'class' => AccessControl::className(), 
  5.     'only' => ['logout'], 
  6.     'rules' => [ 
  7.      [ 
  8.       'actions' => ['logout'], 
  9.       'allow' => true, 
  10.       'roles' => ['@'], 
  11.      ], 
  12.     ], 
  13.    ], 
  14.   ]; 

2、getIsGuest、getIdentity判断是否认证用户

isGuest是自动登录过程中最重要的属性。

在上面的AccessControl访问控制里面通过IsGuest属性来判断是否是认证用户,然后在getIsGuest方法里面是调用getIdentity来获取用户信息,如果不为空就说明是认证用户,否则就是游客(未登录)。

  1. public function getIsGuest($checkSession = true) 
  2.   return $this->getIdentity($checkSession) === null; 
  3. public function getIdentity($checkSession = true) 
  4.   if ($this->_identity === false) { 
  5.    if ($checkSession) { 
  6.     $this->renewAuthStatus(); 
  7.    } else { 
  8.     return null; 
  9.    } 
  10.   } 
  11.   return $this->_identity; 

3、renewAuthStatus 重新生成用户认证信息

  1. protected function renewAuthStatus() 
  2.   $session = Yii::$app->getSession(); 
  3.   $id = $session->getHasSessionId() || $session->getIsActive() ? $session->get($this->idParam) : null; 
  4.   if ($id === null) { 
  5.    $identity = null; 
  6.   } else { 
  7.    /** @var IdentityInterface $class */ 
  8.    $class = $this->identityClass; 
  9.    $identity = $class::findIdentity($id); 
  10.   } 
  11.   $this->setIdentity($identity); 
  12.   if ($this->authTimeout !== null && $identity !== null) { 
  13.    $expire = $session->get($this->authTimeoutParam); 
  14.    if ($expire !== null && $expire < time()) { 
  15.     $this->logout(false); 
  16.    } else { 
  17.     $session->set($this->authTimeoutParam, time() + $this->authTimeout); 
  18.    } 
  19.   } 
  20.   if ($this->enableAutoLogin) { 
  21.    if ($this->getIsGuest()) { 
  22.     $this->loginByCookie(); 
  23.    } elseif ($this->autoRenewCookie) { 
  24.     $this->renewIdentityCookie(); 
  25.    } 
  26.   } 

这一部分先通过session来判断用户,因为用户登录后就已经存在于session中了。然后再判断如果是自动登录,那么就通过cookie信息来登录。

4、通过保存的Cookie信息来登录 loginByCookie

  1. protected function loginByCookie() 
  2.   $name = $this->identityCookie['name']; 
  3.   $value = Yii::$app->getRequest()->getCookies()->getValue($name); 
  4.   if ($value !== null) { 
  5.    $data = json_decode($value, true); 
  6.    if (count($data) === 3 && isset($data[0], $data[1], $data[2])) { 
  7.     list ($id$authKey$duration) = $data
  8.     /** @var IdentityInterface $class */ 
  9.     $class = $this->identityClass; 
  10.     $identity = $class::findIdentity($id); 
  11.     if ($identity !== null && $identity->validateAuthKey($authKey)) { 
  12.      if ($this->beforeLogin($identity, true, $duration)) { 
  13.       $this->switchIdentity($identity$this->autoRenewCookie ? $duration : 0); 
  14.       $ip = Yii::$app->getRequest()->getUserIP(); 
  15.       Yii::info("User '$id' logged in from $ip via cookie."__METHOD__); 
  16.       $this->afterLogin($identity, true, $duration); 
  17.      } 
  18.     } elseif ($identity !== null) { 
  19.      Yii::warning("Invalid auth key attempted for user '$id': $authKey"__METHOD__); 
  20.     } 
  21.    } 
  22.   } 

先读取cookie值,然后$data = json_decode($value, true);反序列化为数组。

这个从上面的代码可以知道要想实现自动登录,这三个值都必须有值,另外,在User Model中还必须要实现findIdentity、validateAuthKey这两个方法。

登录完成后,还可以再重新设置cookie的有效期,这样便能一起有效下去了。

$this->switchIdentity($identity, $this->autoRenewCookie ? $duration : 0);

三、退出 logout

  1. public function logout($destroySession = true) 
  2.   $identity = $this->getIdentity(); 
  3.   if ($identity !== null && $this->beforeLogout($identity)) { 
  4.    $this->switchIdentity(null); 
  5.    $id = $identity->getId(); 
  6.    $ip = Yii::$app->getRequest()->getUserIP(); 
  7.    Yii::info("User '$id' logged out from $ip."__METHOD__); 
  8.    if ($destroySession) { 
  9.     Yii::$app->getSession()->destroy(); 
  10.    } 
  11.    $this->afterLogout($identity); 
  12.   } 
  13.   return $this->getIsGuest(); 
  14. public function switchIdentity($identity$duration = 0) 
  15.   $session = Yii::$app->getSession(); 
  16.   if (!YII_ENV_TEST) { 
  17.    $session->regenerateID(true); 
  18.   } 
  19.   $this->setIdentity($identity); 
  20.   $session->remove($this->idParam); 
  21.   $session->remove($this->authTimeoutParam); 
  22.   if ($identity instanceof IdentityInterface) { 
  23.    $session->set($this->idParam, $identity->getId()); 
  24.    if ($this->authTimeout !== null) { 
  25.     $session->set($this->authTimeoutParam, time() + $this->authTimeout); 
  26.    } 
  27.    if ($duration > 0 && $this->enableAutoLogin) { 
  28.     $this->sendIdentityCookie($identity$duration); 
  29.    } 
  30.   } elseif ($this->enableAutoLogin) { 
  31.    Yii::$app->getResponse()->getCookies()->remove(new Cookie($this->identityCookie)); 
  32.   } 

退出的时候先把当前的认证设置为null,然后再判断如果是自动登录功能则再删除相关的cookie信息。

Tags: Yii2框架登录 Yii2自动登录

分享到: