Yii2框架自動登入以及登入登出功能的實作方法

黄舟
發布: 2023-03-16 18:44:02
原創
2059 人瀏覽過

自動登入的原理很簡單。主要就是利用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()<br/>$identity->getAuthKey()<br/>$duration

getId()和getAuthKey()是在IdentityInterface接口中的。我們也知道在設定User元件的時候,這個User Model是必須要實作IdentityInterface介面的。所以,可以在User Model中得到前兩個值,第三值就是cookie的有效期限。

二、自動從cookie登入

從上面我們知道使用者的認證資訊已經儲存到cookie中了,那麼下次的時候直接從cookie裡面拿資訊然後設定就可以了。

1、AccessControl使用者存取控制

Yii提供了AccessControl來判斷使用者是否登錄,有了這個就不需要在每一個action裡面再判斷了


public function behaviors()
{
  return [
   &#39;access&#39; => [
    &#39;class&#39; => AccessControl::className(),
    &#39;only&#39; => [&#39;logout&#39;],
    &#39;rules&#39; => [
     [
      &#39;actions&#39; => [&#39;logout&#39;],
      &#39;allow&#39; => true,
      &#39;roles&#39; => [&#39;@&#39;],
     ],
    ],
   ],
  ];
}
登入後複製

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[&#39;name&#39;];
  $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 &#39;$id&#39; logged in from $ip via cookie.", __METHOD__);
      $this->afterLogin($identity, true, $duration);
     }
    } elseif ($identity !== null) {
     Yii::warning("Invalid auth key attempted for user &#39;$id&#39;: $authKey", __METHOD__);
    }
   }
  }
}
登入後複製

先讀取cookie值,然後$data = json_decode($value, true);反序列化為陣列。

這個從上面的程式碼可以知道要實現自動登錄,這三個值都必須有值。另外,在User Model中還必須實作findIdentityvalidateAuthKey這兩個方法。

登入完成後,還可以再重新設定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框架自動登入以及登入登出功能的實作方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!