授权
简介
除了提供内置的身份验证服务外,Laravel 还提供了一种简单的方法来授权用户对给定资源执行操作。例如,即使用户已通过身份验证,他们也可能无权更新或删除应用程序管理的某些 Eloquent 模型或数据库记录。Laravel 的授权功能提供了一种简单、有组织的方式来管理这些类型的授权检查。
Laravel 提供了两种主要的授权操作方式:gates 和策略。将 gates 和策略想象成路由和控制器。Gates 提供了一种简单的、基于闭包的授权方法,而策略(如控制器)则围绕特定模型或资源组织逻辑。在本文档中,我们将首先探讨 gates,然后检查策略。
在构建应用程序时,您不需要在只使用 gates 或只使用策略之间做出选择。大多数应用程序很可能包含 gates 和策略的混合,这完全没问题!Gates 最适用于与任何模型或资源无关的操作,例如查看管理员仪表板。相反,当您希望为特定模型或资源授权操作时,应使用策略。
Gates
编写 Gates
WARNING
Gates 是学习 Laravel 授权基础知识的好方法;但是,在构建健壮的 Laravel 应用程序时,您应该考虑使用策略来组织您的授权规则。
Gates 只是确定用户是否有权执行给定操作的闭包。通常,gates 使用 Gate 门面在 App\Providers\AppServiceProvider 类的 boot 方法中定义。Gates 总是接收用户实例作为其第一个参数,并且可以选择接收其他参数,如相关的 Eloquent 模型。
在此示例中,我们将定义一个 gate 来确定用户是否可以更新给定的 App\Models\Post 模型。Gate 将通过将用户的 id 与创建帖子的用户的 user_id 进行比较来实现这一点:
use App\Models\Post;
use App\Models\User;
use Illuminate\Support\Facades\Gate;
/**
* 引导任何应用程序服务。
*/
public function boot(): void
{
Gate::define('update-post', function (User $user, Post $post) {
return $user->id === $post->user_id;
});
}2
3
4
5
6
7
8
9
10
11
12
13
与控制器一样,gates 也可以使用类回调数组定义:
use App\Policies\PostPolicy;
use Illuminate\Support\Facades\Gate;
/**
* 引导任何应用程序服务。
*/
public function boot(): void
{
Gate::define('update-post', [PostPolicy::class, 'update']);
}2
3
4
5
6
7
8
9
10
授权操作
要使用 gates 授权操作,您应该使用 Gate 门面提供的 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
{
/**
* 更新给定帖子。
*/
public function update(Request $request, Post $post): RedirectResponse
{
if (! Gate::allows('update-post', $post)) {
abort(403);
}
// 更新帖子...
return redirect('/posts');
}
}2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
如果您想确定当前已认证用户以外的用户是否有权执行操作,可以使用 Gate 门面上的 forUser 方法:
if (Gate::forUser($user)->allows('update-post', $post)) {
// 用户可以更新帖子...
}
if (Gate::forUser($user)->denies('update-post', $post)) {
// 用户无法更新帖子...
}2
3
4
5
6
7
您可以使用 any 或 none 方法一次授权多个操作:
if (Gate::any(['update-post', 'delete-post'], $post)) {
// 用户可以更新或删除帖子...
}
if (Gate::none(['update-post', 'delete-post'], $post)) {
// 用户无法更新或删除帖子...
}2
3
4
5
6
7
授权或抛出异常
如果您想尝试授权操作并在用户不被允许执行给定操作时自动抛出 Illuminate\Auth\Access\AuthorizationException,可以使用 Gate 门面的 authorize 方法。AuthorizationException 实例由 Laravel 自动转换为 403 HTTP 响应:
Gate::authorize('update-post', $post);
// 操作已授权...2
3
提供额外上下文
授权能力的 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])) {
// 用户可以创建帖子...
}2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
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.');
});2
3
4
5
6
7
8
9
即使从 gate 返回授权响应,Gate::allows 方法仍将返回简单的布尔值;但是,您可以使用 Gate::inspect 方法获取 gate 返回的完整授权响应:
$response = Gate::inspect('edit-settings');
if ($response->allowed()) {
// 操作已授权...
} else {
echo $response->message();
}2
3
4
5
6
7
当使用 Gate::authorize 方法时(如果操作未授权则抛出 AuthorizationException),授权响应提供的错误消息将传播到 HTTP 响应:
Gate::authorize('edit-settings');
// 操作已授权...2
3
自定义 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);
});2
3
4
5
6
7
8
9
因为通过 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();
});2
3
4
5
6
7
8
9
拦截 Gate 检查
有时,您可能希望授予特定用户所有能力。您可以使用 before 方法定义在所有其他授权检查之前运行的闭包:
use App\Models\User;
use Illuminate\Support\Facades\Gate;
Gate::before(function (User $user, string $ability) {
if ($user->isAdministrator()) {
return true;
}
});2
3
4
5
6
7
8
如果 before 闭包返回非 null 结果,则该结果将被视为授权检查的结果。
您可以使用 after 方法定义在所有其他授权检查之后执行的闭包:
use App\Models\User;
Gate::after(function (User $user, string $ability, bool|null $result, mixed $arguments) {
if ($user->isAdministrator()) {
return true;
}
});2
3
4
5
6
7
after 闭包返回的值不会覆盖授权检查的结果,除非 gate 或策略返回 null。
内联授权
有时,您可能希望确定当前已认证用户是否有权执行给定操作,而无需编写与该操作对应的专用 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());2
3
4
5
6
如果操作未授权或当前没有用户认证,Laravel 将自动抛出 Illuminate\Auth\Access\AuthorizationException 异常。AuthorizationException 实例由 Laravel 的异常处理程序自动转换为 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) {
// 返回给定模型的策略类名称...
});2
3
4
5
手动注册策略
使用 Gate 门面,您可以在应用程序的 AppServiceProvider 的 boot 方法中手动注册策略及其相应的模型:
use App\Models\Order;
use App\Policies\OrderPolicy;
use Illuminate\Support\Facades\Gate;
/**
* 引导任何应用程序服务。
*/
public function boot(): void
{
Gate::policy(Order::class, OrderPolicy::class);
}2
3
4
5
6
7
8
9
10
11
或者,您可以将 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
{
//
}2
3
4
5
6
7
8
9
10
11
12
13
编写策略
策略方法
注册策略类后,您可以为其授权的每个操作添加方法。例如,让我们在 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
{
/**
* 确定给定帖子是否可以由用户更新。
*/
public function update(User $user, Post $post): bool
{
return $user->id === $post->user_id;
}
}2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
您可以继续根据其授权的各种操作在策略上定义其他方法。例如,您可能定义 view 或 delete 方法来授权各种 Post 相关操作,但请记住,您可以自由地为策略方法指定任何您喜欢的名称。
如果您在通过 Artisan 控制台生成策略时使用了 --model 选项,它将已经包含 viewAny、view、create、update、delete、restore 和 forceDelete 操作的方法。
NOTE
所有策略都通过 Laravel 服务容器解析,允许您在策略的构造函数中类型提示任何所需的依赖项以自动注入它们。
策略响应
到目前为止,我们只检查了返回简单布尔值的策略方法。但是,有时您可能希望返回更详细的响应,包括错误消息。为此,您可以从策略方法返回 Illuminate\Auth\Access\Response 实例:
use App\Models\Post;
use App\Models\User;
use Illuminate\Auth\Access\Response;
/**
* 确定给定帖子是否可以由用户更新。
*/
public function update(User $user, Post $post): Response
{
return $user->id === $post->user_id
? Response::allow()
: Response::deny('You do not own this post.');
}2
3
4
5
6
7
8
9
10
11
12
13
从策略返回授权响应时,Gate::allows 方法仍将返回简单的布尔值;但是,您可以使用 Gate::inspect 方法获取 gate 返回的完整授权响应:
use Illuminate\Support\Facades\Gate;
$response = Gate::inspect('update', $post);
if ($response->allowed()) {
// 操作已授权...
} else {
echo $response->message();
}2
3
4
5
6
7
8
9
当使用 Gate::authorize 方法时(如果操作未授权则抛出 AuthorizationException),授权响应提供的错误消息将传播到 HTTP 响应:
Gate::authorize('update', $post);
// 操作已授权...2
3
自定义 HTTP 响应状态
当通过策略方法拒绝操作时,返回 403 HTTP 响应;但是,有时返回替代的 HTTP 状态码可能很有用。您可以使用 Illuminate\Auth\Access\Response 类上的 denyWithStatus 静态构造函数自定义失败授权检查返回的 HTTP 状态码:
use App\Models\Post;
use App\Models\User;
use Illuminate\Auth\Access\Response;
/**
* 确定给定帖子是否可以由用户更新。
*/
public function update(User $user, Post $post): Response
{
return $user->id === $post->user_id
? Response::allow()
: Response::denyWithStatus(404);
}2
3
4
5
6
7
8
9
10
11
12
13
因为通过 404 响应隐藏资源是 Web 应用程序的常见模式,所以提供了 denyAsNotFound 方法以方便使用:
use App\Models\Post;
use App\Models\User;
use Illuminate\Auth\Access\Response;
/**
* 确定给定帖子是否可以由用户更新。
*/
public function update(User $user, Post $post): Response
{
return $user->id === $post->user_id
? Response::allow()
: Response::denyAsNotFound();
}2
3
4
5
6
7
8
9
10
11
12
13
无模型方法
某些策略方法只接收当前已认证用户的实例。这种情况在授权 create 操作时最常见。例如,如果您正在创建博客,您可能希望确定用户是否有权创建任何帖子。在这些情况下,您的策略方法应该只期望接收用户实例:
/**
* 确定给定用户是否可以创建帖子。
*/
public function create(User $user): bool
{
return $user->role == 'writer';
}2
3
4
5
6
7
访客用户
默认情况下,如果传入的 HTTP 请求不是由已认证用户发起的,所有 gates 和策略会自动返回 false。但是,您可以通过声明"可选"类型提示或为用户参数定义提供 null 默认值来允许这些授权检查传递给您的 gates 和策略:
<?php
namespace App\Policies;
use App\Models\Post;
use App\Models\User;
class PostPolicy
{
/**
* 确定给定帖子是否可以由用户更新。
*/
public function update(?User $user, Post $post): bool
{
return $user?->id === $post->user_id;
}
}2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
策略过滤器
对于某些用户,您可能希望授权给定策略中的所有操作。为此,请在策略上定义一个 before 方法。before 方法将在策略上的任何其他方法之前执行,使您有机会在实际调用预期的策略方法之前授权操作。此功能最常用于授权应用程序管理员执行任何操作:
use App\Models\User;
/**
* 对用户执行预授权检查。
*/
public function before(User $user, string $ability): bool|null
{
if ($user->isAdministrator()) {
return true;
}
return null;
}2
3
4
5
6
7
8
9
10
11
12
13
如果您想拒绝用户的所有能力,可以从 before 方法返回 false。如果返回 null,授权检查将传递给策略方法。
WARNING
如果策略类不包含与正在检查的能力名称匹配的方法,则不会调用策略类的 before 方法。
使用策略授权操作
通过用户模型
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
{
/**
* 更新给定帖子。
*/
public function update(Request $request, Post $post): RedirectResponse
{
if ($request->user()->cannot('update', $post)) {
abort(403);
}
// 更新帖子...
return redirect('/posts');
}
}2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
如果为给定模型注册了策略,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
{
/**
* 创建帖子。
*/
public function create(Request $request): RedirectResponse
{
if ($request->user()->cannot('create', Post::class)) {
abort(403);
}
// 创建帖子...
return redirect('/posts');
}
}2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
通过 Gate 门面
除了通过 App\Models\User 模型提供的方法外,您还可以始终通过 Gate 门面授权操作。例如,让我们确定用户是否有权更新给定的帖子:
use App\Models\Post;
use Illuminate\Support\Facades\Gate;
if (! Gate::allows('update-post', $post)) {
abort(403);
}2
3
4
5
6
您可以使用 denies 方法确定用户是否未被授权执行给定操作:
if (Gate::denies('update-post', $post)) {
abort(403);
}2
3
当然,allows 和 denies 方法只是 Gate::check 方法的语法糖。check 方法接受三个参数:能力的名称、模型(可选)和允许用户执行操作的回调。
通过中间件
Laravel 包含一个中间件,可以在请求到达路由或控制器之前授权操作。默认情况下,Illuminate\Auth\Middleware\Authorize 中间件被分配了 can 键作为 App\Http\Kernel 类的别名。让我们探索一个使用 can 中间件授权用户可以更新帖子的示例:
use App\Models\Post;
Route::put('/post/{post}', function (Post $post) {
// 当前用户可以更新帖子...
})->middleware('can:update,post');2
3
4
5
在此示例中,我们将两个参数传递给 can 中间件。第一个是我们希望授权的操作名称,第二个是我们希望传递给策略方法的路由参数。在这种情况下,由于我们使用隐式模型绑定,Post 模型将传递给策略方法。如果用户未被授权执行给定操作,中间件将返回带有 403 状态码的 HTTP 响应。
为了方便起见,您还可以使用 can 方法将中间件附加到路由:
use App\Models\Post;
Route::put('/post/{post}', function (Post $post) {
// 当前用户可以更新帖子...
})->can('update', 'post');2
3
4
5
不需要模型的操作
同样,某些策略方法可能对应于不需要模型实例的操作,如 create。在这些情况下,可以将类名传递给中间件。类名将用于确定授权操作时应使用哪个策略:
Route::post('/post', function () {
// 当前用户可以创建帖子...
})->middleware('can:create,App\Models\Post');2
3
在中间件定义中指定整个类名可能很麻烦。因此,您可以选择使用 can 方法将中间件附加到路由:
use App\Models\Post;
Route::post('/post', function () {
// 当前用户可以创建帖子...
})->can('create', Post::class);2
3
4
5
通过 Blade 模板
在编写 Blade 模板时,您可能希望仅在用户被授权执行给定操作时显示页面的一部分。例如,您可能希望仅在用户可以实际更新帖子时显示更新表单。在这种情况下,您可以使用 @can 和 @cannot 指令:
@can('update', $post)
<!-- 当前用户可以更新帖子 -->
@elsecan('create', App\Models\Post::class)
<!-- 当前用户可以创建帖子 -->
@else
<!-- ... -->
@endcan
@cannot('update', $post)
<!-- 当前用户无法更新帖子 -->
@elsecannot('create', App\Models\Post::class)
<!-- 当前用户无法创建帖子 -->
@endcannot2
3
4
5
6
7
8
9
10
11
12
13
这些指令是编写 @if 和 @unless 语句的快捷方式。上面的 @can 和 @cannot 语句分别等同于以下语句:
@if(Auth::user()->can('update', $post))
<!-- 当前用户可以更新帖子 -->
@endif
@unless(Auth::user()->can('update', $post))
<!-- 当前用户无法更新帖子 -->
@endunless2
3
4
5
6
7
您还可以确定用户是否被授权执行给定数组中的任何操作。为此,请使用 @canany 指令:
@canany(['update', 'view'], $post)
<!-- 当前用户可以更新或查看帖子 -->
@elsecanany(['create'], \App\Models\Post::class)
<!-- 当前用户可以创建帖子 -->
@endcanany2
3
4
5
不需要模型的操作
与大多数其他授权方法一样,如果操作不需要模型实例,可以将类名传递给 @can 和 @cannot 指令:
@can('create', App\Models\Post::class)
<!-- 当前用户可以创建帖子 -->
@endcan
@cannot('create', App\Models\Post::class)
<!-- 当前用户无法创建帖子 -->
@endcannot2
3
4
5
6
7
提供额外上下文
在使用策略授权操作时,您可以为各种授权方法和函数提供数组作为第二个参数。数组中的第一个元素将用于确定应调用哪个策略,而其余数组元素作为参数传递给策略方法,并可在做出授权决定时用于额外上下文。例如,考虑以下 PostPolicy 方法定义,其中包含额外的 $category 参数:
/**
* 确定用户是否可以更新给定帖子。
*/
public function update(User $user, Post $post, int $category): bool
{
return $user->id === $post->user_id &&
$user->canUpdateCategory($category);
}2
3
4
5
6
7
8
当尝试确定已认证用户是否可以更新给定帖子时,我们可以这样调用策略方法:
/**
* 更新给定帖子。
*/
public function update(Request $request, Post $post): RedirectResponse
{
$this->authorize('update', [$post, $request->category]);
// 当前用户可以更新博客帖子...
return redirect('/posts');
}2
3
4
5
6
7
8
9
10
11
授权与 Inertia
在向 Inertia.js 驱动的前端授权操作时,您可以在应用程序的中间件中定义一个"共享"数据项,该数据项为每个请求提供授权信息。您可以将此共享数据用作 Inertia 组件中的道具,以授权前端操作。例如,假设我们有一个返回 can 对象的中间件:
<?php
namespace App\Http\Middleware;
use App\Models\Post;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Gate;
use Inertia\Middleware;
class HandleInertiaRequests extends Middleware
{
// ...
/**
* 定义要共享的默认道具。
*
* @return array<string, mixed>
*/
public function share(Request $request): array
{
return [
...parent::share($request),
'can' => [
'create_post' => Gate::check('create', Post::class),
'update_post' => fn (Post $post) => Gate::check('update', $post),
],
];
}
}2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
然后,您可以在 Inertia 组件中使用 can 道具来授权操作:
<script setup>
import { usePage } from '@inertiajs/vue3'
const can = usePage().props.can
</script>
<template>
<div>
<div v-if="can.create_post">
<!-- 创建帖子表单 -->
</div>
</div>
</template>2
3
4
5
6
7
8
9
10
11
12
13
为了方便起见,您还可以使用 HandleInertiaRequests 中间件提供的 can 方法。此方法接受与 Gate::allows 相同的参数,并返回布尔结果:
public function share(Request $request): array
{
return [
...parent::share($request),
'can' => $this->can([
'create_post' => [Post::class],
'update_post' => fn (Post $post) => $post,
]),
];
}2
3
4
5
6
7
8
9
10