前言
Laravel開箱即用的用戶登錄注冊(cè)甚是好用,如果你還不知道如何使用請(qǐng)移步用戶認(rèn)證文檔捂掰。
但筆者發(fā)現(xiàn)一個(gè)問題敢会,remeber_token的問題。remeber_token只要在用戶選擇了記住密碼
的按鈕这嚣,那么只要用戶不退出鸥昏,那么這個(gè)token將持續(xù)五年,意思就是在五年之內(nèi)姐帚,你都可以拿著這個(gè)remeber_token
去登錄這個(gè)賬號(hào)吏垮。顯然,這是不安全的罐旗。
而參照了大多數(shù)網(wǎng)站的做法膳汪,應(yīng)該是每一次登錄,即刷新這個(gè)token九秀,讓一個(gè)token的變?yōu)橐淮涡缘氖挛镆潘浴_@樣能增強(qiáng)登錄驗(yàn)證的安全性。
那在laravel中怎么做呢鼓蜒?
筆者翻閱了源碼痹换,做了諸多實(shí)驗(yàn)之后征字,終于是做到了。但筆者是修改的源碼晴音,如果想要在生產(chǎn)環(huán)境中使用柔纵,不建議這么做缔杉。
本文主要是為了帶大家疏通思路锤躁,看一下源碼。
解決方案
首先查看登錄的源碼部分或详,由于多層調(diào)用系羞,建議使用IDE快速命中。
登陸的核心邏輯在vendor/laravel/framework/src/Illuminate/Auth/SessionGuard.php
之中霸琴,其中的functionattempt
是其具體的實(shí)現(xiàn)邏輯椒振。同文件目錄下的functionlogin
是在用戶比對(duì)完成后,添加session的部分梧乘,這一個(gè)位置比較重要澎迎。
然后,查看auth中間件的邏輯选调。在vendor/laravel/framework/src/Illuminate/Auth/Middleware/Authenticate.php
中夹供,可以看到中間的調(diào)用邏輯。
其最終調(diào)用的是vendor/laravel/framework/src/Illuminate/Auth/SessionGuard.php
的functionuser()
仁堪,
其中
$recaller = $this->recaller();
的邏輯哮洽,是使用request中的cookieremeber_token
與現(xiàn)有的數(shù)據(jù)進(jìn)行比對(duì),當(dāng)比對(duì)成功返回user的信息
弦聂,再將其保存在session中鸟辅。這樣就實(shí)現(xiàn)了,remeber_token的登錄了莺葫。
但需要注意的是此時(shí)匪凉,remeber_token沒有變化,這時(shí)如果想要做到remeber_token跟隨登錄后捺檬,進(jìn)行改變的話再层,那么我們就需要在functionuser()
做一點(diǎn)手腳了。
我們可以模仿登錄欺冀,讓remeber_token能夠進(jìn)行改變树绩。那么只需要將login的邏輯拿過來就ok了。
將functionuser
改寫如下:
...
// If the user is null, but we decrypt a "recaller" cookie we can attempt to
// pull the user data on that cookie which serves as a remember cookie on
// the application. Once we have a user we can return it to the caller.
$recaller = $this->recaller();
if (is_null($user) && ! is_null($recaller)) {
$user = $this->userFromRecaller($recaller);
if ($user) {
// 重新生成token
$this->cycleRememberToken($user);
// 重新定義用戶
$this->setUser($user);
// 刷新cookie
$this->queueRecallerCookie($user);
// 更新session
$this->updateSession($user->getAuthIdentifier());
// 退出登錄事件
$this->fireLoginEvent($user, true);
}
}
return $this->user = $user;
}
當(dāng)完成了這一步隐轩,你的token就能夠隨著登錄而重新刷新了饺饭。
因?yàn)槭切薷牡脑创a,顯然這時(shí)不可取的职车。筆者已向taylor大神發(fā)送了郵件瘫俊,表達(dá)了這個(gè)看法鹊杖,如果taylor大神認(rèn)可的的話,可能再接下來的版本中就能夠看到這一項(xiàng)更新了扛芽。
當(dāng)然骂蓖,如果你現(xiàn)在就要使用的話,不建議修改源碼川尖。建議自己寫一個(gè)記住密碼的功能登下。