Laravel的Auth模塊使用

本文是基于laravel 5.4 版本的auth模塊代碼進(jìn)行分析書寫;

模塊組成

Auth模塊從功能上分為用戶認(rèn)證和權(quán)限管理兩個(gè)部分;從文件組成上,IlluminateAuthPasswords目錄下是密碼重置或忘記密碼處理的小模塊,IlluminateAuth是負(fù)責(zé)用戶認(rèn)證和權(quán)限管理的模塊,IlluminateFoundationAuth提供了登錄、修改密碼、重置密碼等一系統(tǒng)列具體邏輯實(shí)現(xiàn);下圖展示了Auth模塊各個(gè)文件的關(guān)系,并進(jìn)行簡(jiǎn)要說(shuō)明;

Laravel的Auth模塊使用

用戶認(rèn)證

HTTP本身是無(wú)狀態(tài),通常在系統(tǒng)交互的過(guò)程中,使用賬號(hào)或者Token標(biāo)識(shí)來(lái)確定認(rèn)證用戶;

配置文件解讀

return?[ ????'defaults'?=>?[ ????????'guard'?=>?'web', ????????... ????], ????'guards'?=>?[?? ????????'web'?=>?[ ????????????'driver'?=>?'session', ????????????'provider'?=>?'users', ????????], ????????'api'?=>?[???? ????????????'driver'?=>?'token',? ????????????'provider'?=>?'users', ????????], ????], ????'providers'?=>?[ ????????'users'?=>?[ ????????????'driver'?=>?'eloquent', ????????????'model'?=>?AppUser::class, ????????],? ????], ],? ];

從下往上,理解;

providers是提供用戶數(shù)據(jù)的接口,要標(biāo)注驅(qū)動(dòng)對(duì)象和目標(biāo)對(duì)象;此處,鍵名users是一套provider的名字,采用eloquent驅(qū)動(dòng),modal是AppUser::class;

guards部分針對(duì)認(rèn)證管理部分進(jìn)行配置;有兩種認(rèn)證方式,一種叫web,還有一種是api;web認(rèn)證是基于Session交互,根據(jù)sessionId獲取用戶id,在users這個(gè)provider查詢出此用戶;api認(rèn)證是基于token值交互,也采用users這個(gè)provider;

defaults項(xiàng)顯示默認(rèn)使用web認(rèn)證;

認(rèn)證

Session綁定認(rèn)證信息:

//?$credentials數(shù)組存放認(rèn)證條件,比如郵箱或者用戶名、密碼 //?$remember?表示是否要記住,生成?`remember_token` public?function?attempt(array?$credentials?=?[],?$remember?=?false)? ? public?function?login(AuthenticatableContract?$user,?$remember?=?false) ? public?function?loginUsingId($id,?$remember?=?false)

HTTP基本認(rèn)證,認(rèn)證信息放在請(qǐng)求頭部;后面的請(qǐng)求訪問(wèn)通過(guò)sessionId;

public?function?basic($field?=?'email',?$extraConditions?=?[])

只在當(dāng)前會(huì)話中認(rèn)證,session中不記錄認(rèn)證信息:

public?function?once(array?$credentials?=?[]) public?function?onceUsingId($id) public?function?onceBasic($field?=?'email',?$extraConditions?=?[])

認(rèn)證過(guò)程中(包括注冊(cè)、忘記密碼),定義的事件有這些:

Attempting? 嘗試驗(yàn)證事件

Authenticated? ?驗(yàn)證通過(guò)事件

Failed? 驗(yàn)證失敗事件

Lockout 失敗次數(shù)超過(guò)限制,鎖住該請(qǐng)求再次訪問(wèn)事件

Logi? ? 通過(guò)‘remember_token’成功登錄時(shí),調(diào)用的事件

Logout? 用戶退出事件

Registered? 用戶注冊(cè)事件

還有一些其他的認(rèn)證方法:

檢查是否存在認(rèn)證用戶:Auth::check()

獲取當(dāng)前認(rèn)證用戶:Auth::user()

退出系統(tǒng):Auth::logout()

密碼處理

配置解讀

return?[ ????'defaults'?=>?[ ????????'passwords'?=>?'users', ????????... ????], ???? ????'passwords'?=>?[ ????????'users'?=>?[ ????????????'provider'?=>?'users', ????????????'table'?=>?'password_resets', ????????????'expire'?=>?60, ????????], ????], ]

從下往上,看配置;

passwords數(shù)組是重置密碼的配置;users是配置方案的別名,包含三個(gè)元素:provider(提供用戶的方案,是上面providers數(shù)組)、table(存放重置密碼token的表)、expire(token過(guò)期時(shí)間)

default 項(xiàng)會(huì)設(shè)置默認(rèn)的 passwords 重置方案;

重置密碼的調(diào)用與實(shí)現(xiàn)

先看看laravel的重置密碼功能是怎么實(shí)現(xiàn)的:

public?function?reset(array?$credentials,?Closure?$callback)?{ ????//?驗(yàn)證用戶名、密碼和?token?是否有效 ????$user?=?$this->validateReset($credentials); ????if?(!?$user?instanceof?CanResetPasswordContract)?{ ?????????return?$user; ????}???? ???? ????$password?=?$credentials['password']; ????//?回調(diào)函數(shù)執(zhí)行修改密碼,及持久化存儲(chǔ) ????$callback($user,?$password); ????//?刪除重置密碼時(shí)持久化存儲(chǔ)保存的?token ????$this->tokens->delete($user); ????return?static::PASSWORD_RESET; }

再看看FoundationAuth模塊封裝的重置密碼模塊是怎么調(diào)用的:

//?暴露的重置密碼?API public?function?reset(Request?$request)???{ ????//?驗(yàn)證請(qǐng)求參數(shù)?token、email、password、password_confirmation ????$this->validate($request,?$this->rules(),?$this->validationErrorMessages()); ????//?調(diào)用重置密碼的方法,第二個(gè)參數(shù)是回調(diào),做一些持久化存儲(chǔ)工作 ????$response?=?$this->broker()->reset( ????????$this->credentials($request),?function?($user,?$password)?{ ????????$this->resetPassword($user,?$password); ????????} ????); ????//?封裝?Response ????return?$response?==?Password::PASSWORD_RESET ??????????$this->sendResetResponse($response) ????????:?$this->sendResetFailedResponse($request,?$response); } //?獲取重置密碼時(shí)的請(qǐng)求參數(shù) protected?function?credentials(Request?$request)??{ ????return?$request->only( ????????'email',?'password',?'password_confirmation',?'token' ????); } //?重置密碼的真實(shí)性驗(yàn)證后,進(jìn)行的持久化工作 protected?function?resetPassword($user,?$password)?{ ????//?修改后的密碼、重新生成?remember_token ????$user->forceFill([ ????????'password'?=>?bcrypt($password), ????????'remember_token'?=>?Str::random(60), ????])->save(); ????//?session?中的用戶信息也進(jìn)行重新賦值????????????????????????????????????? ????$this->guard()->login($user); }

“忘記密碼 => 發(fā)郵件 => 重置密碼” 的大體流程如下:

點(diǎn)擊“忘記密碼”,通過(guò)路由配置,跳到“忘記密碼”頁(yè)面,頁(yè)面上有“要發(fā)送的郵箱”這個(gè)字段要填寫;

驗(yàn)證“要發(fā)送的郵箱”是否是數(shù)據(jù)庫(kù)中存在的,如果存在,即向該郵箱發(fā)送重置密碼郵件;

重置密碼郵件中有一個(gè)鏈接(點(diǎn)擊后會(huì)攜帶 token 到修改密碼頁(yè)面),同時(shí)數(shù)據(jù)庫(kù)會(huì)保存這個(gè) token 的哈希加密后的值;

填寫“郵箱”,“密碼”,“確認(rèn)密碼”三個(gè)字段后,攜帶 token 訪問(wèn)重置密碼API,首頁(yè)判斷郵箱、密碼、確認(rèn)密碼這三個(gè)字段,然后驗(yàn)證 token是否有效;如果是,則重置成功;

權(quán)限管理

權(quán)限管理是依靠?jī)?nèi)存空間維護(hù)的一個(gè)數(shù)組變量abilities來(lái)維護(hù),結(jié)構(gòu)如下:

$abilities?=?array( ????'定義的動(dòng)作名,比如以路由的?as?名(common.dashboard.list)'?=>?function($user)?{ ????????//?方法的參數(shù),第一位是?$user,?當(dāng)前?user,?后面的參數(shù)可以自行決定 ????????return?true;??//?返回?true?意味有權(quán)限,?false?意味沒(méi)有權(quán)限 ????}, ????...... );

但只用 $abilities,會(huì)使用定義的那部分代碼集中在一起太煩索,所以有policy策略類的出現(xiàn);

policy策略類定義一組實(shí)體及實(shí)體權(quán)限類的對(duì)應(yīng)關(guān)系,比如以文章舉例:

有一個(gè) Modal實(shí)體類叫 Post,可以為這個(gè)實(shí)體類定義一個(gè)PostPolicy權(quán)限類,在這個(gè)權(quán)限類定義一些動(dòng)作為方法名;

class?PostPolicy?{ ????//?update?權(quán)限,文章作者才可以修改 ????public?function?update(User?$user,?Post?$post)?{ ????????return?$user->id?===?$post->user_id; ????} }

然后在ServiceProvider中注冊(cè),這樣系統(tǒng)就知道,如果你要檢查的類是Post對(duì)象,加上你給的動(dòng)作名,系統(tǒng)會(huì)找到PostPolicy類的對(duì)應(yīng)方法;

protected?$policies?=?[ ????Post::class?=>?PostPolicy::class, ];

怎么調(diào)用呢?

對(duì)于定義在abilities數(shù)組的權(quán)限:

當(dāng)前用戶是否具備common.dashboard.list權(quán)限:Gate::allows(‘common.dashboard.list’)

當(dāng)前用戶是否具備common.dashboard.list權(quán)限:! Gate::denies(‘common.dashboard.list’)

當(dāng)前用戶是否具備common.dashboard.list權(quán)限:$request->user()->can(‘common.dashboard.list’)

當(dāng)前用戶是否具備common.dashboard.list權(quán)限:! $request->user()->cannot(‘common.dashboard.list’)

指定用戶是否具備common.dashboard.list權(quán)限:Gate::forUser($user)->allows(‘common.dashboard.list’)

對(duì)于policy策略類調(diào)用的權(quán)限:

當(dāng)前用戶是否可以修改文章(Gate 調(diào)用):Gate::allows(‘update’, $post)

當(dāng)前用戶是否可以修改文章(user 調(diào)用):$user->can(‘update’, $post)

當(dāng)前用戶是否可以修改文章(用幫助函數(shù)):policy($post)->update($user, $post)

當(dāng)前用戶是否可以修改文章(Controller 類方法中調(diào)用):$this->authorize(‘update’, $post);

當(dāng)前用戶是否可以修改文章(Controller 類同名方法中調(diào)用):$this->authorize($post);

指定用戶是否可以修改文章(Controller 類方法中調(diào)用):$this->authorizeForUser($user, ‘update’, $post);

有用的技巧

獲取當(dāng)前系統(tǒng)注冊(cè)的權(quán)限,包括兩部分abilities和policies數(shù)組內(nèi)容,代碼如下:

$gate?=?app(IlluminateContractsAuthAccessGate::class); $reflection_gate?=?new?ReflectionClass($gate); $policies?=?$reflection_gate->getProperty('policies'); $policies->setAccessible(true); //?獲取當(dāng)前注冊(cè)的?policies?數(shù)組 dump($policies->getValue($gate)); ???????????????????????????????????????????????????????????????????????????????????????????????????????? $abilities?=?$reflection_gate->getProperty('abilities');??????????????????????????????????????? $abilities->setAccessible(true); //?獲取當(dāng)前注冊(cè)的?abilities?數(shù)組 dump($abilities->getValue($gate));

推薦教程:《Laravel教程

? 版權(quán)聲明
THE END
喜歡就支持一下吧
點(diǎn)贊10 分享