授权
简介
除了提供内置的 认证 服务外,Laravel 还提供了一种简单的方式,用于针对给定资源授权用户操作。例如,即使用户已通过认证,也可能无权更新或删除应用管理的某些 Eloquent 模型或数据库记录。Laravel 的授权功能提供了简便、有条理的方式来管理这类授权检查。
Laravel 提供了两种主要的操作授权方式:Gates 与 策略(Policies)。可以把 Gates 和策略类比为路由与控制器。Gates 提供基于闭包的简单授权方式;而策略则像控制器一样,围绕特定模型或资源组织逻辑。本文档将先介绍 Gates,再介绍策略。
构建应用时,你不必在「只用 Gates」或「只用策略」之间二选一。大多数应用很可能同时使用 Gates 与策略的某种组合,这完全没问题!Gates 最适合与任何模型或资源无关的操作,例如查看管理员仪表盘。相对地,当你希望针对特定模型或资源授权某项操作时,应使用策略。
Gates
编写 Gates
WARNING
Gates 是学习 Laravel 授权功能基础的好方式;不过,在构建稳健的 Laravel 应用时,你应考虑使用 策略 来组织授权规则。
Gates 本质上是判断用户是否有权执行给定操作的闭包。通常,Gates 在 App\Providers\AppServiceProvider 类的 boot 方法中,通过 Gate facade 定义。Gates 始终以用户实例作为第一个参数,并可选择接收额外参数,例如相关的 Eloquent 模型。
本例中,我们将定义一个 Gate,判断用户是否可以更新给定的 App\Models\Post 模型。该 Gate 通过比较用户的 id 与创建该文章的用户的 user_id 来完成判断:
use App\Models\Post;
use App\Models\User;
use Illuminate\Support\Facades\Gate;
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Gate::define('update-post', function (User $user, Post $post) {
return $user->id === $post->user_id;
});
}与控制器类似,Gates 也可以使用类回调数组来定义:
use App\Policies\PostPolicy;
use Illuminate\Support\Facades\Gate;
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Gate::define('update-post', [PostPolicy::class, 'update']);
}授权操作
要使用 Gates 授权操作,应使用 Gate facade 提供的 allows 或 denies 方法。注意,你无需向这些方法传入当前已认证用户。Laravel 会自动将该用户传入 Gate 闭包。通常在应用的控制器中,于执行需要授权的操作之前调用这些 Gate 授权方法:
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
class PostController extends Controller
{
/**
* Update the given post.
*/
public function update(Request $request, Post $post): RedirectResponse
{
if (! Gate::allows('update-post', $post)) {
abort(403);
}
// Update the post...
return redirect('/posts');
}
}若要判断当前已认证用户以外的某个用户是否有权执行某项操作,可使用 Gate facade 的 forUser 方法:
if (Gate::forUser($user)->allows('update-post', $post)) {
// The user can update the post...
}
if (Gate::forUser($user)->denies('update-post', $post)) {
// The user can't update the post...
}你可以使用 any 或 none 方法一次授权多项操作:
if (Gate::any(['update-post', 'delete-post'], $post)) {
// The user can update or delete the post...
}
if (Gate::none(['update-post', 'delete-post'], $post)) {
// The user can't update or delete the post...
}授权或抛出异常
若希望尝试授权某项操作,并在用户无权执行该操作时自动抛出 Illuminate\Auth\Access\AuthorizationException,可使用 Gate facade 的 authorize 方法。Laravel 会自动将 AuthorizationException 实例转换为 403 HTTP 响应:
Gate::authorize('update-post', $post);
// The action is authorized...提供额外上下文
用于授权能力(ability)的 Gate 方法(allows、denies、check、any、none、authorize、can、cannot)以及授权 Blade 指令(@can、@cannot、@canany)可以将数组作为第二个参数。这些数组元素会作为参数传入 Gate 闭包,并可在做出授权决策时用作额外上下文:
use App\Models\Category;
use App\Models\User;
use Illuminate\Support\Facades\Gate;
Gate::define('create-post', function (User $user, Category $category, bool $pinned) {
if (! $user->canPublishToGroup($category->group)) {
return false;
} elseif ($pinned && ! $user->canPinPosts()) {
return false;
}
return true;
});
if (Gate::check('create-post', [$category, $pinned])) {
// The user can create the post...
}Gate 响应
到目前为止,我们只讨论了返回简单布尔值的 Gates。不过,有时你可能希望返回更详细的响应,包括错误消息。为此,可以从 Gate 返回 Illuminate\Auth\Access\Response:
use App\Models\User;
use Illuminate\Auth\Access\Response;
use Illuminate\Support\Facades\Gate;
Gate::define('edit-settings', function (User $user) {
return $user->isAdmin
? Response::allow()
: Response::deny('You must be an administrator.');
});即使从 Gate 返回授权响应,Gate::allows 方法仍会返回简单的布尔值;不过,你可以使用 Gate::inspect 方法获取 Gate 返回的完整授权响应:
$response = Gate::inspect('edit-settings');
if ($response->allowed()) {
// The action is authorized...
} else {
echo $response->message();
}使用会在操作未获授权时抛出 AuthorizationException 的 Gate::authorize 方法时,授权响应提供的错误消息会传播到 HTTP 响应中:
Gate::authorize('edit-settings');
// The action is authorized...自定义 HTTP 响应状态码
当通过 Gate 拒绝某项操作时,会返回 403 HTTP 响应;不过,有时返回其他 HTTP 状态码会更有用。你可以使用 Illuminate\Auth\Access\Response 类上的 denyWithStatus 静态构造方法,自定义授权检查失败时返回的 HTTP 状态码:
use App\Models\User;
use Illuminate\Auth\Access\Response;
use Illuminate\Support\Facades\Gate;
Gate::define('edit-settings', function (User $user) {
return $user->isAdmin
? Response::allow()
: Response::denyWithStatus(404);
});由于通过 404 响应隐藏资源是 Web 应用中非常常见的模式,因此还提供了便捷的 denyAsNotFound 方法:
use App\Models\User;
use Illuminate\Auth\Access\Response;
use Illuminate\Support\Facades\Gate;
Gate::define('edit-settings', function (User $user) {
return $user->isAdmin
? Response::allow()
: Response::denyAsNotFound();
});拦截 Gate 检查
有时,你可能希望授予特定用户全部能力。可以使用 before 方法定义一个在所有其他授权检查之前运行的闭包:
use App\Models\User;
use Illuminate\Support\Facades\Gate;
Gate::before(function (User $user, string $ability) {
if ($user->isAdministrator()) {
return true;
}
});若 before 闭包返回非 null 结果,该结果将被视为授权检查的结果。
你可以使用 after 方法定义一个在所有其他授权检查之后执行的闭包:
use App\Models\User;
Gate::after(function (User $user, string $ability, bool|null $result, mixed $arguments) {
if ($user->isAdministrator()) {
return true;
}
});除非 Gate 或策略返回了 null,否则 after 闭包返回的值不会覆盖授权检查的结果。
内联授权
偶尔,你可能希望判断当前已认证用户是否有权执行给定操作,而又不想为该操作编写专用 Gate。Laravel 允许你通过 Gate::allowIf 和 Gate::denyIf 方法执行此类「内联」授权检查。内联授权不会执行任何已定义的 「before」或「after」授权钩子:
use App\Models\User;
use Illuminate\Support\Facades\Gate;
Gate::allowIf(fn (User $user) => $user->isAdministrator());
Gate::denyIf(fn (User $user) => $user->banned());若操作未获授权,或当前没有已认证用户,Laravel 会自动抛出 Illuminate\Auth\Access\AuthorizationException 异常。Laravel 的异常处理器会自动将 AuthorizationException 实例转换为 403 HTTP 响应。
创建策略
生成策略
策略是围绕特定模型或资源组织授权逻辑的类。例如,若你的应用是博客,你可能有一个 App\Models\Post 模型,以及对应的 App\Policies\PostPolicy,用于授权创建或更新文章等用户操作。
你可以使用 make:policy Artisan 命令生成策略。生成的策略将放在 app/Policies 目录中。若应用中不存在该目录,Laravel 会为你创建:
php artisan make:policy PostPolicymake:policy 命令会生成一个空的策略类。若希望生成包含与查看、创建、更新和删除资源相关的示例策略方法的类,可在执行命令时提供 --model 选项:
php artisan make:policy PostPolicy --model=Post注册策略
策略发现
默认情况下,只要模型与策略遵循 Laravel 标准命名约定,Laravel 就会自动发现策略。具体而言,策略必须位于包含模型的目录或其上级目录中的 Policies 目录下。例如,模型可放在 app/Models 目录,策略可放在 app/Policies 目录。在此情况下,Laravel 会先检查 app/Models/Policies,再检查 app/Policies。此外,策略名称必须与模型名称匹配,并带有 Policy 后缀。因此,User 模型会对应 UserPolicy 策略类。
若希望自定义策略发现逻辑,可使用 Gate::guessPolicyNamesUsing 方法注册自定义策略发现回调。通常应在应用的 AppServiceProvider 的 boot 方法中调用该方法:
use Illuminate\Support\Facades\Gate;
Gate::guessPolicyNamesUsing(function (string $modelClass) {
// Return the name of the policy class for the given model...
});手动注册策略
使用 Gate facade,你可以在应用的 AppServiceProvider 的 boot 方法中手动注册策略及其对应模型:
use App\Models\Order;
use App\Policies\OrderPolicy;
use Illuminate\Support\Facades\Gate;
/**
* Bootstrap any application services.
*/
public function boot(): void
{
Gate::policy(Order::class, OrderPolicy::class);
}或者,你可以在模型类上放置 UsePolicy 属性,以告知 Laravel 该模型对应的策略:
<?php
namespace App\Models;
use App\Policies\OrderPolicy;
use Illuminate\Database\Eloquent\Attributes\UsePolicy;
use Illuminate\Database\Eloquent\Model;
#[UsePolicy(OrderPolicy::class)]
class Order extends Model
{
//
}编写策略
策略方法
策略类注册完成后,你可以为它授权的每项操作添加方法。例如,我们在 PostPolicy 上定义一个 update 方法,用于判断给定的 App\Models\User 是否可以更新给定的 App\Models\Post 实例。
update 方法将接收一个 User 和一个 Post 实例作为参数,并应返回 true 或 false,以表明用户是否有权更新给定的 Post。因此,在本例中,我们将验证用户的 id 是否与文章上的 user_id 匹配:
<?php
namespace App\Policies;
use App\Models\Post;
use App\Models\User;
class PostPolicy
{
/**
* Determine if the given post can be updated by the user.
*/
public function update(User $user, Post $post): bool
{
return $user->id === $post->user_id;
}
}你可以根据策略授权的各种操作,继续在策略上定义额外方法。例如,你可以定义 view 或 delete 方法来授权各种与 Post 相关的操作,但请记住,你可以为策略方法任意命名。
若通过 Artisan 控制台生成策略时使用了 --model 选项,策略中将已包含 viewAny、view、create、update、delete、restore 和 forceDelete 操作对应的方法。
INFO
所有策略都通过 Laravel 服务容器 解析,因此你可以在策略的构造函数中对所需依赖进行类型提示,以便自动注入。
策略响应
到目前为止,我们只讨论了返回简单布尔值的策略方法。不过,有时你可能希望返回更详细的响应,包括错误消息。为此,可以从策略方法返回 Illuminate\Auth\Access\Response 实例:
use App\Models\Post;
use App\Models\User;
use Illuminate\Auth\Access\Response;
/**
* Determine if the given post can be updated by the user.
*/
public function update(User $user, Post $post): Response
{
return $user->id === $post->user_id
? Response::allow()
: Response::deny('You do not own this post.');
}从策略返回授权响应时,Gate::allows 方法仍会返回简单的布尔值;不过,你可以使用 Gate::inspect 方法获取 Gate 返回的完整授权响应:
use Illuminate\Support\Facades\Gate;
$response = Gate::inspect('update', $post);
if ($response->allowed()) {
// The action is authorized...
} else {
echo $response->message();
}使用会在操作未获授权时抛出 AuthorizationException 的 Gate::authorize 方法时,授权响应提供的错误消息会传播到 HTTP 响应中:
Gate::authorize('update', $post);
// The action is authorized...自定义 HTTP 响应状态码
当通过策略方法拒绝某项操作时,会返回 403 HTTP 响应;不过,有时返回其他 HTTP 状态码会更有用。你可以使用 Illuminate\Auth\Access\Response 类上的 denyWithStatus 静态构造方法,自定义授权检查失败时返回的 HTTP 状态码:
use App\Models\Post;
use App\Models\User;
use Illuminate\Auth\Access\Response;
/**
* Determine if the given post can be updated by the user.
*/
public function update(User $user, Post $post): Response
{
return $user->id === $post->user_id
? Response::allow()
: Response::denyWithStatus(404);
}由于通过 404 响应隐藏资源是 Web 应用中非常常见的模式,因此还提供了便捷的 denyAsNotFound 方法:
use App\Models\Post;
use App\Models\User;
use Illuminate\Auth\Access\Response;
/**
* Determine if the given post can be updated by the user.
*/
public function update(User $user, Post $post): Response
{
return $user->id === $post->user_id
? Response::allow()
: Response::denyAsNotFound();
}不依赖模型的方法
某些策略方法只接收当前已认证用户的实例。这种情况在授权 create 操作时最为常见。例如,若你在创建博客,可能希望判断用户是否有权创建任何文章。在这些情况下,策略方法应只期望接收一个用户实例:
/**
* Determine if the given user can create posts.
*/
public function create(User $user): bool
{
return $user->role == 'writer';
}访客用户
默认情况下,若传入的 HTTP 请求并非由已认证用户发起,所有 Gates 和策略都会自动返回 false。不过,你可以通过为用户参数声明「可选」类型提示,或提供 null 默认值,让这些授权检查继续传递到 Gates 和策略:
<?php
namespace App\Policies;
use App\Models\Post;
use App\Models\User;
class PostPolicy
{
/**
* Determine if the given post can be updated by the user.
*/
public function update(?User $user, Post $post): bool
{
return $user?->id === $post->user_id;
}
}策略过滤器
对于某些用户,你可能希望授权给定策略中的全部操作。为此,可在策略上定义 before 方法。before 方法会在策略上的任何其他方法之前执行,使你有机会在目标策略方法实际被调用之前授权该操作。该功能最常用于授权应用管理员执行任意操作:
use App\Models\User;
/**
* Perform pre-authorization checks.
*/
public function before(User $user, string $ability): bool|null
{
if ($user->isAdministrator()) {
return true;
}
return null;
}若希望拒绝某一类用户的全部授权检查,可从 before 方法返回 false。若返回 null,授权检查将继续落到策略方法上。
WARNING
若策略类不包含与所检查能力名称匹配的方法,则不会调用该策略类的 before 方法。
使用策略授权操作
通过 User 模型
Laravel 应用自带的 App\Models\User 模型包含两个用于授权操作的实用方法:can 与 cannot。can 与 cannot 方法接收你希望授权的操作名称以及相关模型。例如,我们来判断用户是否有权更新给定的 App\Models\Post 模型。通常这会在控制器方法中完成:
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
class PostController extends Controller
{
/**
* Update the given post.
*/
public function update(Request $request, Post $post): RedirectResponse
{
if ($request->user()->cannot('update', $post)) {
abort(403);
}
// Update the post...
return redirect('/posts');
}
}若已为给定模型 注册策略,can 方法会自动调用相应策略并返回布尔结果。若未为该模型注册策略,can 方法会尝试调用与给定操作名称匹配的基于闭包的 Gate。
不需要模型的操作
请记住,某些操作可能对应像 create 这样不需要模型实例的策略方法。在这些情况下,你可以将类名传给 can 方法。该类名将用于确定授权该操作时应使用哪个策略:
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
class PostController extends Controller
{
/**
* Create a post.
*/
public function store(Request $request): RedirectResponse
{
if ($request->user()->cannot('create', Post::class)) {
abort(403);
}
// Create the post...
return redirect('/posts');
}
}通过 Gate Facade
除了 App\Models\User 模型提供的实用方法外,你始终可以通过 Gate facade 的 authorize 方法授权操作。
与 can 方法类似,该方法接受你希望授权的操作名称以及相关模型。若操作未获授权,authorize 方法会抛出 Illuminate\Auth\Access\AuthorizationException 异常,Laravel 异常处理器会自动将其转换为状态码为 403 的 HTTP 响应:
<?php
namespace App\Http\Controllers;
use App\Models\Post;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
class PostController extends Controller
{
/**
* Update the given blog post.
*
* @throws \Illuminate\Auth\Access\AuthorizationException
*/
public function update(Request $request, Post $post): RedirectResponse
{
Gate::authorize('update', $post);
// The current user can update the blog post...
return redirect('/posts');
}
}不需要模型的操作
如前所述,某些策略方法(如 create)不需要模型实例。在这些情况下,你应将类名传给 authorize 方法。该类名将用于确定授权该操作时应使用哪个策略:
use App\Models\Post;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
/**
* Create a new blog post.
*
* @throws \Illuminate\Auth\Access\AuthorizationException
*/
public function create(Request $request): RedirectResponse
{
Gate::authorize('create', Post::class);
// The current user can create blog posts...
return redirect('/posts');
}通过中间件
Laravel 包含一个可在传入请求到达路由或控制器之前授权操作的中间件。默认情况下,可使用 can 中间件别名(由 Laravel 自动注册)将 Illuminate\Auth\Middleware\Authorize 中间件附加到路由。我们来看一个使用 can 中间件授权用户可更新文章的示例:
use App\Models\Post;
Route::put('/post/{post}', function (Post $post) {
// The current user may update the post...
})->middleware('can:update,post');本例中,我们向 can 中间件传递了两个参数。第一个是希望授权的操作名称,第二个是希望传给策略方法的路由参数。在此情况下,由于我们使用了 隐式模型绑定,一个 App\Models\Post 模型将被传给策略方法。若用户无权执行给定操作,中间件将返回状态码为 403 的 HTTP 响应。
为方便起见,你也可以使用 can 方法将 can 中间件附加到路由:
use App\Models\Post;
Route::put('/post/{post}', function (Post $post) {
// The current user may update the post...
})->can('update', 'post');若你使用 控制器中间件属性,可通过 Authorize 属性应用 can 中间件:
use Illuminate\Routing\Attributes\Controllers\Authorize;
#[Authorize('update', 'post')]
public function update(Post $post)
{
// The current user may update the post...
}不需要模型的操作
同样,某些策略方法(如 create)不需要模型实例。在这些情况下,你可以将类名传给中间件。该类名将用于确定授权该操作时应使用哪个策略:
Route::post('/post', function () {
// The current user may create posts...
})->middleware('can:create,App\Models\Post');在字符串中间件定义中指定完整类名可能会显得繁琐。因此,你可以选择使用 can 方法将 can 中间件附加到路由:
use App\Models\Post;
Route::post('/post', function () {
// The current user may create posts...
})->can('create', Post::class);通过 Blade 模板
编写 Blade 模板时,你可能希望仅在用户有权执行给定操作时才显示页面的某一部分。例如,你可能希望仅在用户确实可以更新文章时才显示博客文章的更新表单。在这种情况下,可以使用 @can 和 @cannot 指令:
@can('update', $post)
<!-- The current user can update the post... -->
@elsecan('create', App\Models\Post::class)
<!-- The current user can create new posts... -->
@else
<!-- ... -->
@endcan
@cannot('update', $post)
<!-- The current user cannot update the post... -->
@elsecannot('create', App\Models\Post::class)
<!-- The current user cannot create new posts... -->
@endcannot这些指令是编写 @if 和 @unless 语句的便捷快捷方式。上面的 @can 和 @cannot 语句等价于以下语句:
@if (Auth::user()->can('update', $post))
<!-- The current user can update the post... -->
@endif
@unless (Auth::user()->can('update', $post))
<!-- The current user cannot update the post... -->
@endunless你还可以判断用户是否有权执行给定操作数组中的任一操作。为此,请使用 @canany 指令:
@canany(['update', 'view', 'delete'], $post)
<!-- The current user can update, view, or delete the post... -->
@elsecanany(['create'], \App\Models\Post::class)
<!-- The current user can create a post... -->
@endcanany不需要模型的操作
与大多数其他授权方法一样,若操作不需要模型实例,你可以将类名传给 @can 和 @cannot 指令:
@can('create', App\Models\Post::class)
<!-- The current user can create posts... -->
@endcan
@cannot('create', App\Models\Post::class)
<!-- The current user can't create posts... -->
@endcannot提供额外上下文
使用策略授权操作时,你可以将数组作为第二个参数传给各种授权函数与辅助方法。数组的第一个元素将用于确定应调用哪个策略,而其余数组元素会作为参数传给策略方法,并可在做出授权决策时用作额外上下文。例如,考虑以下包含额外 $category 参数的 PostPolicy 方法定义:
/**
* Determine if the given post can be updated by the user.
*/
public function update(User $user, Post $post, int $category): bool
{
return $user->id === $post->user_id &&
$user->canUpdateCategory($category);
}在判断已认证用户是否可以更新给定文章时,可以像这样调用该策略方法:
/**
* Update the given blog post.
*
* @throws \Illuminate\Auth\Access\AuthorizationException
*/
public function update(Request $request, Post $post): RedirectResponse
{
Gate::authorize('update', [$post, $request->category]);
// The current user can update the blog post...
return redirect('/posts');
}授权与 Inertia
尽管授权必须始终在服务端处理,但向前端应用提供授权数据以便正确渲染应用 UI 通常也很方便。Laravel 并未规定向基于 Inertia 的前端暴露授权信息的强制约定。
不过,若你使用 Laravel 基于 Inertia 的 起步套件 之一,应用中已包含 HandleInertiaRequests 中间件。在该中间件的 share 方法中,你可以返回将提供给应用中所有 Inertia 页面的共享数据。这些共享数据可作为定义用户授权信息的便捷位置:
<?php
namespace App\Http\Middleware;
use App\Models\Post;
use Illuminate\Http\Request;
use Inertia\Middleware;
class HandleInertiaRequests extends Middleware
{
// ...
/**
* Define the props that are shared by default.
*
* @return array<string, mixed>
*/
public function share(Request $request)
{
return [
...parent::share($request),
'auth' => [
'user' => $request->user(),
'permissions' => [
'post' => [
'create' => $request->user()->can('create', Post::class),
],
],
],
];
}
}