搜尋
首頁後端開發php教程Yii2框架實現登入、登出及自動登入功能

本文主要介紹了Yii2框架實現登入、登出及自動登入功能的方法,結合實例形式詳細分析了Yii2框架實現登入、登出及自動登入功能的原理、實現方法與相關操作注意事項,需要的朋友可以參考下,希望能幫助大家。

本文實例講述了Yii2框架實作登入、登出及自動登入功能的方法。分享給大家供大家參考,具體如下:

自動登入的原理很簡單。主要就是利用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框架实现可逆加密的简单方法分享

使用YII2框架开发实现微信公众号中表单提交功能教程详解

Yii2框架中日志的使用方法分析

以上是Yii2框架實現登入、登出及自動登入功能的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
使用PHP發送電子郵件的最佳方法是什麼?使用PHP發送電子郵件的最佳方法是什麼?May 08, 2025 am 12:21 AM

ThebestapproachforsendingemailsinPHPisusingthePHPMailerlibraryduetoitsreliability,featurerichness,andeaseofuse.PHPMailersupportsSMTP,providesdetailederrorhandling,allowssendingHTMLandplaintextemails,supportsattachments,andenhancessecurity.Foroptimalu

PHP中依賴注入的最佳實踐PHP中依賴注入的最佳實踐May 08, 2025 am 12:21 AM

使用依賴注入(DI)的原因是它促進了代碼的松耦合、可測試性和可維護性。 1)使用構造函數注入依賴,2)避免使用服務定位器,3)利用依賴注入容器管理依賴,4)通過注入依賴提高測試性,5)避免過度注入依賴,6)考慮DI對性能的影響。

PHP性能調整技巧和技巧PHP性能調整技巧和技巧May 08, 2025 am 12:20 AM

phpperformancetuningiscialbecapeitenhancesspeedandeffice,whatevitalforwebapplications.1)cachingwithapcureduccureducesdatabaseloadprovesrovessetimes.2)優化

PHP電子郵件安全性:發送電子郵件的最佳實踐PHP電子郵件安全性:發送電子郵件的最佳實踐May 08, 2025 am 12:16 AM

ThebestpracticesforsendingemailssecurelyinPHPinclude:1)UsingsecureconfigurationswithSMTPandSTARTTLSencryption,2)Validatingandsanitizinginputstopreventinjectionattacks,3)EncryptingsensitivedatawithinemailsusingOpenSSL,4)Properlyhandlingemailheaderstoa

您如何優化PHP應用程序的性能?您如何優化PHP應用程序的性能?May 08, 2025 am 12:08 AM

TOOPTIMIZEPHPAPPLICITIONSFORPERSTORANCE,USECACHING,數據庫imization,opcodecaching和SererverConfiguration.1)InlumentCachingWithApcutCutoredSatfetchTimes.2)優化的atabasesbasesebasesebasesbasesbasesbaysbysbyIndexing,BeallancingAndWriteExing

PHP中的依賴注入是什麼?PHP中的依賴注入是什麼?May 07, 2025 pm 03:09 PM

依賴性注射inphpisadesignpatternthatenhancesFlexibility,可檢驗性和ManiaginabilybyByByByByByExternalDependencEctenceScoupling.itallowsforloosecoupling,EasiererTestingThroughMocking,andModularDesign,andModularDesign,butquirscarecarefulscarefullsstructoringDovairing voavoidOverOver-Inje

最佳PHP性能優化技術最佳PHP性能優化技術May 07, 2025 pm 03:05 PM

PHP性能優化可以通過以下步驟實現:1)在腳本頂部使用require_once或include_once減少文件加載次數;2)使用預處理語句和批處理減少數據庫查詢次數;3)配置OPcache進行opcode緩存;4)啟用並配置PHP-FPM優化進程管理;5)使用CDN分發靜態資源;6)使用Xdebug或Blackfire進行代碼性能分析;7)選擇高效的數據結構如數組;8)編寫模塊化代碼以優化執行。

PHP性能優化:使用OpCode緩存PHP性能優化:使用OpCode緩存May 07, 2025 pm 02:49 PM

opcodecachingsimplovesphperforvesphpermance bycachingCompiledCode,reducingServerLoadAndResponSetimes.1)itstorescompiledphpcodeinmemory,bypassingparsingparsingparsingandcompiling.2)useopcachebachebachebachebachebachebachebysettingparametersinphametersinphp.ini,likeememeryconmorysmorysmeryplement.33)

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

將Eclipse與SAP NetWeaver應用伺服器整合。

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境