本文主要介紹了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 [ 'access' => [ 'class' => AccessControl::className(), 'only' => ['logout'], 'rules' => [ [ 'actions' => ['logout'], 'allow' => true, 'roles' => ['@'], ], ], ], ]; }
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['name']; $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 '$id' logged in from $ip via cookie.", __METHOD__); $this->afterLogin($identity, true, $duration); } } elseif ($identity !== null) { Yii::warning("Invalid auth key attempted for user '$id': $authKey", __METHOD__); } } } }
先讀取cookie值,然後$data = json_decode($value, true);
反序列化為陣列。
這個從上面的程式碼可以知道要實現自動登錄,這三個值都必須有值。另外,在User Model中還必須實作findIdentity、validateAuthKey這兩個方法。
登入完成後,還可以再重新設定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中文網其他相關文章!

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

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

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

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

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

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

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

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


熱AI工具

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

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

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

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

熱門文章

熱工具

Dreamweaver CS6
視覺化網頁開發工具

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

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

記事本++7.3.1
好用且免費的程式碼編輯器

禪工作室 13.0.1
強大的PHP整合開發環境