本文是基於Laravel 5.4
版本的Auth
模塊代碼進行分析書寫;web
Auth
模塊從功能上分爲用戶認證和權限管理兩個部分;從文件組成上,Illuminate\Auth\Passwords
目錄下是密碼重置或忘記密碼處理的小模塊,Illuminate\Auth
是負責用戶認證和權限管理的模塊,Illuminate\Foundation\Auth
提供了登陸、修改密碼、重置密碼等一系統列具體邏輯實現;下圖展現了Auth
模塊各個文件的關係,並進行簡要說明;數據庫
HTTP
自己是無狀態,一般在系統交互的過程當中,使用帳號或者Token
標識來肯定認證用戶;api
return [ 'defaults' => [ 'guard' => 'web', ... ], 'guards' => [ 'web' => [ 'driver' => 'session', 'provider' => 'users', ], 'api' => [ 'driver' => 'token', 'provider' => 'users', ], ], 'providers' => [ 'users' => [ 'driver' => 'eloquent', 'model' => App\User::class, ], ], ], ];
從下往上,理解;數組
providers
是提供用戶數據的接口,要標註驅動對象和目標對象;此處,鍵名users
是一套provider
的名字,採用eloquent
驅動,modal
是App\User::class
;session
guards
部分針對認證管理部分進行配置;有兩種認證方式,一種叫web
,還有一種是api
;web
認證是基於Session
交互,根據sessionId
獲取用戶id
,在users
這個provider
查詢出此用戶;api
認證是基於token
值交互,也採用users
這個provider
;app
defaults
項顯示默認使用web
認證;dom
Session
綁定認證信息:ide
// $credentials數組存放認證條件,好比郵箱或者用戶名、密碼 // $remember 表示是否要記住,生成 `remember_token` public function attempt(array $credentials = [], $remember = false) public function login(AuthenticatableContract $user, $remember = false) public function loginUsingId($id, $remember = false)
HTTP
基本認證,認證信息放在請求頭部;後面的請求訪問經過sessionId
;函數
public function basic($field = 'email', $extraConditions = [])
只在當前會話中認證,session
中不記錄認證信息:post
public function once(array $credentials = []) public function onceUsingId($id) public function onceBasic($field = 'email', $extraConditions = [])
認證過程當中(包括註冊、忘記密碼),定義的事件有這些:
事件名 | 描述 |
---|---|
Attempting | 嘗試驗證事件 |
Authenticated | 驗證經過事件 |
Failed | 驗證失敗事件 |
Lockout | 失敗次數超過限制,鎖住該請求再次訪問事件 |
Logi | 經過‘remember_token’成功登陸時,調用的事件 |
Logout | 用戶退出事件 |
Registered | 用戶註冊事件 |
還有一些其餘的認證方法:
Auth::check()
Auth::user()
Auth::logout()
return [ 'defaults' => [ 'passwords' => 'users', ... ], 'passwords' => [ 'users' => [ 'provider' => 'users', 'table' => 'password_resets', 'expire' => 60, ], ], ]
從下往上,看配置;
passwords
數組是重置密碼的配置;users
是配置方案的別名,包含三個元素:provider
(提供用戶的方案,是上面providers
數組)、table
(存放重置密碼token
的表)、expire
(token
過時時間)
default
項會設置默認的 passwords
重置方案;
先看看Laravel
的重置密碼功能是怎麼實現的:
public function reset(array $credentials, Closure $callback) { // 驗證用戶名、密碼和 token 是否有效 $user = $this->validateReset($credentials); if (! $user instanceof CanResetPasswordContract) { return $user; } $password = $credentials['password']; // 回調函數執行修改密碼,及持久化存儲 $callback($user, $password); // 刪除重置密碼時持久化存儲保存的 token $this->tokens->delete($user); return static::PASSWORD_RESET; }
再看看Foundation\Auth
模塊封裝的重置密碼模塊是怎麼調用的:
// 暴露的重置密碼 API public function reset(Request $request) { // 驗證請求參數 token、email、password、password_confirmation $this->validate($request, $this->rules(), $this->validationErrorMessages()); // 調用重置密碼的方法,第二個參數是回調,作一些持久化存儲工做 $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); } // 獲取重置密碼時的請求參數 protected function credentials(Request $request) { return $request->only( 'email', 'password', 'password_confirmation', 'token' ); } // 重置密碼的真實性驗證後,進行的持久化工做 protected function resetPassword($user, $password) { // 修改後的密碼、從新生成 remember_token $user->forceFill([ 'password' => bcrypt($password), 'remember_token' => Str::random(60), ])->save(); // session 中的用戶信息也進行從新賦值 $this->guard()->login($user); }
「忘記密碼 => 發郵件 => 重置密碼」 的大致流程以下:
token
訪問重置密碼API
,首頁判斷郵箱、密碼、確認密碼這三個字段,而後驗證 token
是否有效;若是是,則重置成功;權限管理是依靠內存空間維護的一個數組變量abilities
來維護,結構以下:
$abilities = array( '定義的動做名,好比以路由的 as 名(common.dashboard.list)' => function($user) { // 方法的參數,第一位是 $user, 當前 user, 後面的參數能夠自行決定 return true; // 返回 true 意味有權限, false 意味沒有權限 }, ...... );
但只用 $abilities
,會使用定義的那部分代碼集中在一塊兒太煩索,因此有policy
策略類的出現;
policy
策略類定義一組實體及實體權限類的對應關係,好比以文章舉例:
有一個 Modal
實體類叫 Post
,能夠爲這個實體類定義一個PostPolicy
權限類,在這個權限類定義一些動做爲方法名;
class PostPolicy { // update 權限,文章做者才能夠修改 public function update(User $user, Post $post) { return $user->id === $post->user_id; } }
而後在ServiceProvider
中註冊,這樣系統就知道,若是你要檢查的類是Post
對象,加上你給的動做名,系統會找到PostPolicy
類的對應方法;
protected $policies = [ Post::class => PostPolicy::class, ];
怎麼調用呢?
對於定義在abilities
數組的權限:
common.dashboard.list
權限:Gate::allows('common.dashboard.list')
common.dashboard.list
權限:! Gate::denies('common.dashboard.list')
common.dashboard.list
權限:$request->user()->can('common.dashboard.list')
common.dashboard.list
權限:! $request->user()->cannot('common.dashboard.list')
common.dashboard.list
權限:Gate::forUser($user)->allows('common.dashboard.list')
對於policy
策略類調用的權限:
Gate::allows('update', $post)
$user->can('update', $post)
policy($post)->update($user, $post)
$this->authorize('update', $post);
$this->authorize($post);
$this->authorizeForUser($user, 'update', $post);
獲取當前系統註冊的權限,包括兩部分abilities
和policies
數組內容,代碼以下:
$gate = app(\Illuminate\Contracts\Auth\Access\Gate::class); $reflection_gate = new ReflectionClass($gate); $policies = $reflection_gate->getProperty('policies'); $policies->setAccessible(true); // 獲取當前註冊的 policies 數組 dump($policies->getValue($gate)); $abilities = $reflection_gate->getProperty('abilities'); $abilities->setAccessible(true); // 獲取當前註冊的 abilities 數組 dump($abilities->getValue($gate));