Laravel 使用者授權系統使用小結
官方文件
Laravel 5.5 文件
ofollow,noindex">https://laravel-china.org/docs/laravel/5.5/authorization/1310
基本用法
示例
$this->authorize('update', $post);
第一個引數 $ability,表示具備什麼許可權。第二個引數 $post,是一個模型例項。
不需指定模型的動作,比如 create,不需要指定的模型。第二個引數傳一個類名。如:
$this->authorize('create', Post::class);
使用的場景有:控制器輔助方法,中介軟體,Blade模板,User 模型的 can 和 can’t 方法。
authorize方法:
public function authorize($ability, $arguments = []) { list($ability, $arguments) = $this->parseAbilityAndArguments($ability, $arguments); return app(Gate::class)->authorize($ability, $arguments); }
有兩種方式實現使用者授權
Gates
編寫 Gates
一般在 app\Providers\AuthServiceProvider 的 boot 方法中定義。
發生錯誤,請稍後重試。
第一個引數是許可權的名稱,第二個引數是滿足許可權的條件,可以是閉包,控制器方法。
授權動作
allows 和 denies 兩種方法,表示允許和否定。
第一個引數是許可權的名稱,第二個引數是模型,可以為空。這裡不需要傳入使用者,框架會自動處理。
if (Gate::allows('update-post', $post)) { // 指定使用者可以更新部落格... } if (Gate::denies('update-post', $post)) { // 指定使用者不能更新部落格... }
如果需要指定特定使用者,可以使用 Gate Facade 中的 forUser 方法:
if (Gate::forUser($user)->allows('update-post', $post)) { // 指定使用者可以更新部落格... } if (Gate::forUser($user)->denies('update-post', $post)) { // 指定使用者不能更新部落格... }
策略
生成策略
artisan 命令:
php artisan make:policy PostPolicy
也可以指定 model,生成包含 CURD 的策略方法。
註冊策略
在 AuthServiceProvider 的 policies 屬性,可以將模型和策略對應起來。如:
protected $policies = [ Post::class => PostPolicy::class, ];
策略方法
public function update(User $user, Post $post) { return $user->id === $post->user_id; }
策略方法,就是許可權名稱,$this->authorize(‘update’, $post) 的第一個引數就對應同名的策略方法,第二個引數 $post 代表它是一個 Post 模型,框架會根據引數判斷採用 Post::class => PostPolicy::class 這個策略。
當 authorize 方法呼叫的時候,實際上會自動注入 User 和 Post 型別的兩個引數,也因此使用授權系統必須是使用者登入的情況下 。
使用策略也不一定要和模型繫結,比如這樣也可以:
protected $policies = [ Travel::class => TravelPolicy::class, 'aaa'=>TravelPolicy::class, ];
這個 aaa 字串對應策略類為 TravelPolicy::class,在控制器使用 authorize 判斷授權:
$this->authorize('update','aaa');
此時也是可行的,第二個引數這個時候就必須是字串 aaa 了,然後 authorize 方法只會自動注入 User 引數。